express-file-cluster 0.9.6 → 0.10.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/dist/auth/index.cjs +5 -5
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +4 -4
- package/dist/{chunk-QL6EWT4B.cjs → chunk-4DOHQU6I.cjs} +9 -7
- package/dist/chunk-4DOHQU6I.cjs.map +1 -0
- package/dist/{chunk-2SETEVMO.js → chunk-7KC2H76D.js} +42 -2
- package/dist/chunk-7KC2H76D.js.map +1 -0
- package/dist/{chunk-6KHBJOLB.cjs → chunk-7KO4DJRJ.cjs} +7 -7
- package/dist/{chunk-6KHBJOLB.cjs.map → chunk-7KO4DJRJ.cjs.map} +1 -1
- package/dist/{chunk-45BWAR6P.js → chunk-ATVD2HGC.js} +3 -3
- package/dist/{chunk-BBSZLGZW.js → chunk-EGSSZUVO.js} +8 -6
- package/dist/chunk-EGSSZUVO.js.map +1 -0
- package/dist/{chunk-TI24L4XE.cjs → chunk-GBI77W5T.cjs} +6 -2
- package/dist/chunk-GBI77W5T.cjs.map +1 -0
- package/dist/{chunk-VWSUQKCJ.cjs → chunk-HBCY7ILD.cjs} +274 -107
- package/dist/chunk-HBCY7ILD.cjs.map +1 -0
- package/dist/{chunk-RGT4ZVHL.cjs → chunk-KFVFP2Q7.cjs} +45 -5
- package/dist/chunk-KFVFP2Q7.cjs.map +1 -0
- package/dist/{chunk-TYCYYLLM.cjs → chunk-NKLOE4AK.cjs} +1 -1
- package/dist/chunk-NKLOE4AK.cjs.map +1 -0
- package/dist/{chunk-OFA7OGN5.js → chunk-PGJQK36V.js} +171 -4
- package/dist/chunk-PGJQK36V.js.map +1 -0
- package/dist/{chunk-ULWNHN6P.js → chunk-QDEDOHP7.js} +1 -1
- package/dist/chunk-QDEDOHP7.js.map +1 -0
- package/dist/{chunk-7ZESZG3J.js → chunk-R4XO4SVM.js} +3 -3
- package/dist/chunk-R52CUEGT.js +74 -0
- package/dist/chunk-R52CUEGT.js.map +1 -0
- package/dist/{chunk-HBYSKULC.js → chunk-RAB44UGX.js} +5 -1
- package/dist/chunk-RAB44UGX.js.map +1 -0
- package/dist/{chunk-7YEX4MQV.cjs → chunk-WBLUGOAG.cjs} +42 -6
- package/dist/chunk-WBLUGOAG.cjs.map +1 -0
- package/dist/{chunk-FMA76PRH.cjs → chunk-YK4ZM3CA.cjs} +8 -8
- package/dist/{chunk-FMA76PRH.cjs.map → chunk-YK4ZM3CA.cjs.map} +1 -1
- package/dist/cli/db-runner.cjs +2010 -116
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +1987 -93
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +36 -13
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +33 -10
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/collection.md +44 -1
- package/dist/docs/api-reference/ignite.md +9 -0
- package/dist/docs/api-reference/types.md +99 -0
- package/dist/docs/cli/add.md +1 -1
- package/dist/docs/cli/db.md +2 -2
- package/dist/docs/core-concepts/background-tasks.md +6 -3
- package/dist/docs/getting-started/index.md +2 -1
- package/dist/docs/guides/caching.md +32 -1
- package/dist/docs/guides/database.md +2 -0
- package/dist/docs/guides/feature-matrix.md +58 -0
- package/dist/docs/guides/migrations.md +23 -2
- package/dist/docs/guides/which-api.md +2 -2
- package/dist/docs/index.md +3 -1
- package/dist/docs/skills/SKILL.md +1 -1
- package/dist/docs/skills/api-surface.md +5 -0
- package/dist/docs/skills/tasks-internals.md +4 -3
- package/dist/docs/skills/what-not-to-invent.md +4 -3
- package/dist/index.cjs +99 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +204 -3
- package/dist/index.d.ts +204 -3
- package/dist/index.js +76 -7
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-FW42SBSM.js +14 -0
- package/dist/pgboss-backend-RVHUBJTU.cjs +14 -0
- package/dist/{pgboss-backend-DSO3QTNK.cjs.map → pgboss-backend-RVHUBJTU.cjs.map} +1 -1
- package/dist/registry/index.json +13 -1
- package/dist/registry/js-mongo/auth.json +1 -1
- package/dist/registry/js-mongo/forgot-password.json +1 -1
- package/dist/registry/js-mongo-collection/_base.json +1 -0
- package/dist/registry/js-mongo-collection/account-security.json +1 -0
- package/dist/registry/js-mongo-collection/account-settings.json +1 -0
- package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/js-mongo-collection/admin-content.json +1 -0
- package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/js-mongo-collection/admin-support.json +1 -0
- package/dist/registry/js-mongo-collection/admin-system.json +1 -0
- package/dist/registry/js-mongo-collection/admin-users.json +1 -0
- package/dist/registry/js-mongo-collection/admin.json +1 -0
- package/dist/registry/js-mongo-collection/auth.json +1 -0
- package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/js-mongo-collection/auth@google.json +1 -0
- package/dist/registry/js-mongo-collection/billing.json +1 -0
- package/dist/registry/js-mongo-collection/email-client.json +1 -0
- package/dist/registry/js-mongo-collection/email-verification.json +1 -0
- package/dist/registry/js-mongo-collection/files.json +1 -0
- package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/js-mongo-collection/notifications.json +1 -0
- package/dist/registry/js-mongo-collection/support.json +1 -0
- package/dist/registry/js-mongo-collection/user-profile.json +1 -0
- package/dist/registry/js-pg-model/auth.json +1 -1
- package/dist/registry/js-pg-model/forgot-password.json +1 -1
- package/dist/registry/js-pg-table/auth.json +1 -1
- package/dist/registry/js-pg-table/forgot-password.json +1 -1
- package/dist/registry/ts-mongo/auth.json +1 -1
- package/dist/registry/ts-mongo/forgot-password.json +1 -1
- package/dist/registry/ts-mongo-collection/_base.json +1 -0
- package/dist/registry/ts-mongo-collection/account-security.json +1 -0
- package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
- package/dist/registry/ts-mongo-collection/admin.json +1 -0
- package/dist/registry/ts-mongo-collection/auth.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
- package/dist/registry/ts-mongo-collection/billing.json +1 -0
- package/dist/registry/ts-mongo-collection/email-client.json +1 -0
- package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
- package/dist/registry/ts-mongo-collection/files.json +1 -0
- package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/ts-mongo-collection/notifications.json +1 -0
- package/dist/registry/ts-mongo-collection/support.json +1 -0
- package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/auth.json +1 -1
- package/dist/registry/ts-pg-model/forgot-password.json +1 -1
- package/dist/registry/ts-pg-table/auth.json +1 -1
- package/dist/registry/ts-pg-table/forgot-password.json +1 -1
- package/dist/tasks/index.cjs +4 -2
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +4 -2
- package/dist/tasks/index.d.ts +4 -2
- package/dist/tasks/index.js +3 -1
- package/dist/thread-runner.cjs +8 -0
- package/dist/thread-runner.cjs.map +1 -0
- package/dist/thread-runner.d.cts +3 -0
- package/dist/thread-runner.d.ts +3 -0
- package/dist/thread-runner.js +8 -0
- package/dist/thread-runner.js.map +1 -0
- package/dist/{types-DAsBKVM-.d.cts → types-Bnxvj3l0.d.cts} +7 -1
- package/dist/{types-DAsBKVM-.d.ts → types-Bnxvj3l0.d.ts} +7 -1
- package/package.json +1 -1
- package/dist/chunk-2SETEVMO.js.map +0 -1
- package/dist/chunk-7YEX4MQV.cjs.map +0 -1
- package/dist/chunk-BBSZLGZW.js.map +0 -1
- package/dist/chunk-HBYSKULC.js.map +0 -1
- package/dist/chunk-LJNSJFOL.js +0 -38
- package/dist/chunk-LJNSJFOL.js.map +0 -1
- package/dist/chunk-OFA7OGN5.js.map +0 -1
- package/dist/chunk-QL6EWT4B.cjs.map +0 -1
- package/dist/chunk-RGT4ZVHL.cjs.map +0 -1
- package/dist/chunk-TI24L4XE.cjs.map +0 -1
- package/dist/chunk-TYCYYLLM.cjs.map +0 -1
- package/dist/chunk-ULWNHN6P.js.map +0 -1
- package/dist/chunk-VWSUQKCJ.cjs.map +0 -1
- package/dist/pgboss-backend-DSO3QTNK.cjs +0 -14
- package/dist/pgboss-backend-I6DFUNRM.js +0 -14
- /package/dist/{chunk-45BWAR6P.js.map → chunk-ATVD2HGC.js.map} +0 -0
- /package/dist/{chunk-7ZESZG3J.js.map → chunk-R4XO4SVM.js.map} +0 -0
- /package/dist/{pgboss-backend-I6DFUNRM.js.map → pgboss-backend-FW42SBSM.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/router/validate.ts","../src/router/mount.ts","../src/cluster/index.ts","../src/tasks/scanner.ts","../src/dashboard.ts","../src/cache/response.ts","../src/compose.ts"],"sourcesContent":["import type http from 'node:http';\nimport fs from 'node:fs';\nimport express from 'express';\nimport cors from 'cors';\nimport cookieParser from 'cookie-parser';\nimport cluster from 'node:cluster';\nimport os from 'node:os';\nimport path from 'node:path';\nimport type { EFCConfig, MountedRoute } from './types.js';\nexport type {\n TableModel,\n TableRecord,\n TableCreateInput,\n TableWhere,\n TableWhereUnique,\n TableUpdateData,\n TableCreateData,\n TableUpdateInput,\n TableOrderBy,\n TableSelect,\n TableInclude,\n TableResult,\n Tables,\n TableFindManyArgs,\n TableAggregateArgs,\n TableGroupByArgs,\n TableAggregateResult,\n ScalarFilter,\n StringFilter,\n ListFilter,\n JsonFilter,\n InferTableRecord,\n} from './table-types.js';\nimport { scanDir } from './router/scan.js';\nimport { mountRoutes } from './router/mount.js';\nimport { runMaster, shutdownMaster } from './cluster/index.js';\nimport { configureAuth } from './auth/index.js';\nimport { isHttpError } from './errors.js';\nimport { connectMongo } from './db/mongo.js';\nimport { setDbClient } from './db/index.js';\nimport { setDbEngine, setAutoSync } from './db/engine.js';\nimport { checkConnectionBudget, connectPostgres } from './db/postgres.js';\nimport { runWithContext } from './context.js';\nimport { configureLogger, getLogger, requestLogger } from './logger.js';\nimport { configureQueryLog } from './db/query-log.js';\nimport { scanTasks } from './tasks/scanner.js';\nimport { initBullMQ, closeBullMQ } from './tasks/bullmq-backend.js';\nimport { initPgBoss, closePgBoss } from './tasks/pgboss-backend.js';\nimport { configureCache, closeCache } from './cache/index.js';\nimport { servePrimaryCache } from './cache/ipc.js';\nimport { generateDashboard } from './dashboard.js';\n\nfunction detectDatabase(url?: string): 'mongodb' | 'postgresql' | undefined {\n if (!url) return undefined;\n if (url.startsWith('mongodb')) return 'mongodb';\n if (url.startsWith('postgres')) return 'postgresql';\n return undefined;\n}\n\nexport async function ignite(config: EFCConfig): Promise<http.Server | undefined> {\n const {\n port: _port,\n workers,\n globalMiddlewares = [],\n onWorkerReady,\n onWorkerCrash,\n onError,\n } = config;\n\n // Resolve api/tasks dirs from convention. argv[1]-based resolution is unreliable in tsx watch\n // + cluster workers (argv[1] can point to the tsx binary instead of the user's script), so we\n // probe multiple candidates and use the first that exists on disk.\n function resolveConventionDir(name: string): string {\n const candidates: string[] = [\n ...(process.argv[1] ? [path.join(path.dirname(process.argv[1]), name)] : []),\n path.join(process.cwd(), 'src', name),\n path.join(process.cwd(), name),\n path.join(process.cwd(), 'dist', name),\n ];\n return candidates.find((c) => fs.existsSync(c)) ?? candidates[0]!;\n }\n const apiDir = resolveConventionDir('api');\n const tasksDir = resolveConventionDir('tasks');\n const basePath = config.basePath ?? '/v1/api';\n\n function readProjectMeta(): { name: string; version: string } {\n try {\n const raw = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');\n const pkg = JSON.parse(raw) as { name?: string; version?: string };\n return { name: pkg.name ?? 'API', version: pkg.version ?? '' };\n } catch {\n return { name: 'API', version: '' };\n }\n }\n\n const port = _port != null && !Number.isNaN(_port) ? _port : 3000;\n const databaseUrl = config.databaseUrl;\n const database = config.database ?? detectDatabase(databaseUrl);\n const jwtSecret = config.jwtSecret;\n const authStrategy = config.authStrategy ?? 'http-only';\n // NODE_ENV is a Node/Express-wide runtime-mode signal set by the platform, not an app\n // secret — unlike PORT/DATABASE_URL/JWT_SECRET/etc. this one is still read directly.\n const clusterEnabled = config.cluster ?? process.env['NODE_ENV'] === 'production';\n\n configureLogger(config.logging);\n // Any value but 'http-only' acts as bearer, as it always has — an app may rely on that, so\n // 0.9.x only warns (a typo of 'http-only' silently means no cookie). 1.0 makes it an error.\n if (\n !['http-only', 'bearer', 'localStorage'].includes(authStrategy) &&\n (!clusterEnabled || cluster.isPrimary) // once, not once per worker\n ) {\n getLogger().warn(\n `[EFC] Unknown authStrategy \"${String(authStrategy)}\" — treated as 'bearer'. Use 'http-only' or 'bearer'; this will be an error in 1.0.`,\n );\n }\n // HS256 with a short secret can be brute-forced offline from any token a user holds.\n if (\n jwtSecret &&\n Buffer.byteLength(jwtSecret) < 32 &&\n process.env['NODE_ENV'] === 'production' &&\n (!clusterEnabled || cluster.isPrimary)\n ) {\n getLogger().warn(\n `[EFC] jwtSecret is ${Buffer.byteLength(jwtSecret)} bytes — use at least 32 random bytes in production (openssl rand -hex 64).`,\n );\n }\n configureQueryLog(config.logging);\n\n if (clusterEnabled && cluster.isPrimary) {\n // The memory cache lives in the primary so all workers share it (cache/ipc.ts).\n if (config.cache && config.cache.backend === 'memory') {\n servePrimaryCache(config.cache.maxEntries ?? 10_000);\n }\n runMaster({\n workers: workers ?? os.cpus().length,\n ...(onWorkerReady !== undefined && { onWorkerReady }),\n ...(onWorkerCrash !== undefined && { onWorkerCrash }),\n });\n return;\n }\n\n const app = express();\n // defineTable returns `bigint` for bigint columns and bigserial ids, which JSON.stringify\n // rejects; send them as strings (exact — a JS number would lose precision past 2^53).\n app.set('json replacer', (_key: string, value: unknown) =>\n typeof value === 'bigint' ? value.toString() : value,\n );\n\n // Wraps every request in its own AsyncLocalStorage context, first thing, so\n // requireAuth (below) and any downstream code — including a `$currentUser`\n // default resolved inside a mongoose `.create()` call — share the same store.\n app.use((_req, _res, next) => {\n runWithContext({}, next);\n });\n app.use(requestLogger());\n\n if (config.requestTimeout) {\n const ms = config.requestTimeout;\n app.use((_req, res, next) => {\n const timer = setTimeout(() => {\n if (!res.headersSent) res.status(408).json({ error: 'Request Timeout', statusCode: 408 });\n }, ms);\n const clear = () => clearTimeout(timer);\n res.once('finish', clear);\n res.once('close', clear);\n next();\n });\n }\n\n const corsOption = config.cors ?? true;\n if (corsOption !== false) {\n const origin =\n typeof corsOption === 'object' && corsOption.origin !== undefined ? corsOption.origin : true;\n const corsOpts = typeof corsOption === 'object' ? { ...corsOption, origin } : { origin };\n app.use(cors(corsOpts));\n }\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n app.use(cookieParser());\n\n for (const mw of globalMiddlewares) {\n app.use(mw);\n }\n\n // Pre-Flight step 1: Connect database. The engine decides what defineModel compiles to.\n if (database) setDbEngine(database);\n setAutoSync(config.autoSync ?? true);\n // Pools are per worker; one process per machine reports the machine's total.\n const poolWorkers = clusterEnabled ? (workers ?? os.cpus().length) : 1;\n const reportsPools = !clusterEnabled || cluster.worker?.id === 1;\n if (database === 'mongodb' && databaseUrl) {\n const conn = await connectMongo(databaseUrl, config.databasePool);\n setDbClient(conn as unknown as Record<string, unknown>);\n if (reportsPools) {\n const max = config.databasePool?.max ?? 100; // mongoose's maxPoolSize default\n getLogger().info(\n `MongoDB connections: up to ${poolWorkers * max} from this machine (${poolWorkers} worker(s) × maxPoolSize ${max})`,\n );\n }\n } else if (database === 'postgresql' && databaseUrl) {\n const pool = await connectPostgres(databaseUrl, config.databasePool);\n setDbClient(pool as unknown as Record<string, unknown>);\n if (reportsPools) {\n const max = config.databasePool?.max ?? 10; // node-postgres' default\n // pg-boss on the same database opens its own pool (node-postgres default 10).\n const boss =\n config.tasks && config.tasks.backend === 'pg-boss' && !config.tasks.connectionString\n ? 10\n : 0;\n const breakdown = `${poolWorkers} worker(s) × (pool ${max}${boss ? ` + pg-boss ${boss}` : ''})`;\n await checkConnectionBudget(poolWorkers * (max + boss), breakdown);\n }\n }\n\n // Pre-Flight step 1b: Cache (also the session-revocation store requireAuth consults)\n if (config.cache) {\n await configureCache(config.cache);\n }\n\n // Pre-Flight step 2: Configure auth\n if (jwtSecret) {\n configureAuth({\n secret: jwtSecret,\n strategy: authStrategy,\n expiresIn: config.jwtExpiresIn ?? '7d',\n ...(config.cookieDomain !== undefined && { cookieDomain: config.cookieDomain }),\n });\n }\n\n // Pre-Flight step 3: Scan and register tasks\n if (tasksDir) {\n await scanTasks(tasksDir);\n }\n\n // Pre-Flight step 4: Start task queue backend\n if (config.tasks) {\n if (config.tasks.backend === 'bullmq') {\n await initBullMQ({\n redisUrl: config.tasks.redisUrl ?? 'redis://localhost:6379',\n concurrency: config.tasks.concurrency ?? 5,\n enqueueTimeout: config.tasks.enqueueTimeout ?? 5000,\n queue: config.tasks.queue ?? 'efc',\n });\n } else if (config.tasks.backend === 'pg-boss') {\n const connectionString = config.tasks.connectionString ?? databaseUrl;\n if (!connectionString) {\n throw new Error(\n '[EFC] tasks.backend \"pg-boss\" needs tasks.connectionString or databaseUrl',\n );\n }\n await initPgBoss({\n connectionString,\n concurrency: config.tasks.concurrency ?? 5,\n enqueueTimeout: config.tasks.enqueueTimeout ?? 5000,\n queue: config.tasks.queue ?? 'efc',\n ...(config.tasks.schema !== undefined && { schema: config.tasks.schema }),\n });\n }\n }\n\n // Pre-Flight step 5: Scan routes and mount\n const routes = scanDir(apiDir);\n const apiRouter = express.Router();\n const mounted: MountedRoute[] = await mountRoutes(apiRouter, routes);\n app.use(basePath, apiRouter);\n\n if (config.dashboard !== false && process.env['NODE_ENV'] === 'development') {\n app.get('/', (_req, res) => {\n const { name, version } = readProjectMeta();\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.send(generateDashboard(mounted, basePath, port, name, version));\n });\n }\n\n if (onError) {\n app.use(onError);\n } else {\n app.use(\n (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {\n // e.g. a handler that kept going after requestTimeout already answered 408.\n if (res.headersSent) {\n getLogger().warn({ err }, 'Error after the response was sent');\n return;\n }\n // isHttpError() covers the common case, but errors can also arrive as plain\n // objects with a numeric statusCode (e.g. thrown across a module boundary, or\n // duck-typed by user code) — fall back to that shape before giving up to 500.\n // Only 4xx: a library's 5xx message can describe internals (hosts, SQL, paths).\n const status = (err as { statusCode?: unknown } | null)?.statusCode;\n const duckTyped =\n err instanceof Error && typeof status === 'number' && status >= 400 && status < 500\n ? (err as Error & { statusCode: number })\n : null;\n\n if (isHttpError(err)) {\n // ModelValidationError carries per-field issues; surface them like route validation does.\n const issues = (err as { issues?: unknown }).issues;\n res.status(err.statusCode).json({\n error: err.message,\n statusCode: err.statusCode,\n ...(issues !== undefined && { issues }),\n });\n } else if (duckTyped) {\n res\n .status(duckTyped.statusCode)\n .json({ error: duckTyped.message, statusCode: duckTyped.statusCode });\n } else {\n getLogger().error({ err }, 'Unhandled error');\n res.status(500).json({ error: 'Internal Server Error', statusCode: 500 });\n }\n },\n );\n }\n\n return new Promise<http.Server>((resolve, reject) => {\n const server = app.listen(port);\n\n server.once('listening', () => {\n const wid = (cluster.worker as { id: number } | undefined)?.id ?? 'primary';\n const addr = server.address() as { port: number } | null;\n getLogger().info(`Worker ${wid} listening on :${addr?.port ?? port}`);\n resolve(server);\n });\n\n server.once('error', reject);\n });\n}\n\nexport function gracefulShutdown(server: http.Server | undefined, timeoutMs = 10_000): void {\n let shuttingDown = false;\n const shutdown = (signal: string) => {\n // A worker can get the signal twice (process-group Ctrl+C plus the primary's\n // forward); the default handler for a repeat would kill it mid-drain.\n if (shuttingDown) return;\n shuttingDown = true;\n getLogger().info(`${signal} received — closing server gracefully…`);\n if (server) {\n server.closeIdleConnections();\n server.close(() => {\n getLogger().info('Server closed');\n // Let in-flight task jobs finish before exiting; the timeout below still caps it.\n Promise.all([closeBullMQ(), closePgBoss(), closeCache()])\n .catch((err: unknown) => getLogger().error({ err }, 'Task backend close failed'))\n .finally(() => process.exit(0));\n });\n setTimeout(() => {\n getLogger().error('Forced exit after timeout');\n process.exit(1);\n }, timeoutMs).unref();\n } else {\n shutdownMaster();\n // Workers get the same budget plus a margin before the primary gives up on them.\n setTimeout(() => {\n getLogger().error('Workers did not exit in time — forcing primary exit');\n process.exit(1);\n }, timeoutMs + 2_000).unref();\n }\n };\n process.on('SIGTERM', () => shutdown('SIGTERM'));\n process.on('SIGINT', () => shutdown('SIGINT'));\n}\n\nexport { HttpError, isHttpError } from './errors.js';\nexport { logger, getLogger } from './logger.js';\nexport { cache } from './cache/index.js';\nexport { cacheResponse } from './cache/response.js';\nexport { compose } from './compose.js';\nexport {\n db,\n setDbClient,\n getDbClient,\n defineModel,\n defineTable,\n defineCollection,\n} from './db/index.js';\nexport type {\n CollectionModel,\n CollectionOptions,\n CollectionFilter,\n CollectionUpdate,\n CollectionFindOptions,\n CollectionWriteResult,\n CollectionBulkResult,\n CollectionBulkOp,\n CollectionChange,\n CollectionChangeStream,\n} from './db/collection-model.js';\nexport { transaction } from './db/transaction.js';\nexport { ModelValidationError } from './db/schema.js';\nexport { scanDir } from './router/scan.js';\nexport { listTasks } from './tasks/index.js';\nexport { workerCount } from './cluster/index.js';\nexport type {\n EFCConfig,\n DatabasePoolConfig,\n CollectionSchema,\n CollectionFieldDefinition,\n GeoPoint,\n CorsConfig,\n RouteEntry,\n RouteMeta,\n RouteMethodMeta,\n RouteSchema,\n LoggingConfig,\n QueryLogConfig,\n CacheConfig,\n RequestSchema,\n Validator,\n ValidationIssue,\n TaskOptions,\n TaskDefinition,\n DatabaseEngine,\n AuthStrategy,\n ModelSchema,\n TableSchema,\n TableSchemaField,\n TableFieldDefinition,\n TableOptions,\n TableRelation,\n MigrationContext,\n SchemaField,\n Filter,\n FilterOperators,\n Update,\n FindOptions,\n IndexDefinition,\n ModelRecord,\n InferRecord,\n InferCreate,\n InferSchema,\n InferCreateInput,\n ScalarKeys,\n SortDirection,\n ModelCRUD,\n ModelQueryOptions,\n ModelOptions,\n FieldDefinition,\n DefaultOperator,\n} from './types.js';\n","import type { Request, RequestHandler } from 'express';\nimport type { RequestSchema, RouteSchema, ValidationIssue, Validator } from '../types.js';\n\nconst LOCATIONS = ['params', 'query', 'body'] as const;\ntype Location = (typeof LOCATIONS)[number];\n\ninterface StandardResult {\n value?: unknown;\n issues?: ReadonlyArray<{\n message: string;\n path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n }>;\n}\n\nfunction isRequestSchema(value: unknown): value is RequestSchema {\n return (\n value != null &&\n typeof value === 'object' &&\n LOCATIONS.some((loc) => loc in (value as Record<string, unknown>))\n );\n}\n\n/** Picks the schema for `method`: a method-keyed entry wins over a file-wide one. */\nexport function schemaFor(\n schema: RouteSchema | undefined,\n method: string,\n): RequestSchema | undefined {\n if (!schema) return undefined;\n const byMethod = (schema as Record<string, unknown>)[method];\n if (isRequestSchema(byMethod)) return byMethod;\n return isRequestSchema(schema) ? schema : undefined;\n}\n\ntype IssuePath = ReadonlyArray<PropertyKey | { key: PropertyKey }> | undefined;\n\nfunction pathToString(path: IssuePath): string {\n if (!path) return '';\n return path\n .map((p) => (typeof p === 'object' && p !== null && 'key' in p ? p.key : p))\n .map(String)\n .join('.');\n}\n\n// Standard Schema (zod >=3.24, valibot, arktype, ...) first; plain zod-style\n// safeParse as a fallback so older zod 3 releases work too.\nasync function run(validator: Validator, input: unknown): Promise<StandardResult> {\n const std = (validator as { '~standard'?: { validate: (v: unknown) => unknown } })['~standard'];\n if (std && typeof std.validate === 'function') {\n return (await std.validate(input)) as StandardResult;\n }\n const v = validator as {\n safeParseAsync?: (x: unknown) => Promise<unknown>;\n safeParse?: (x: unknown) => unknown;\n };\n const parse = v.safeParseAsync ?? v.safeParse;\n if (typeof parse !== 'function') {\n throw new Error('[EFC] Route schema entries must be Standard Schema validators (e.g. zod)');\n }\n const r = (await parse.call(validator, input)) as {\n success: boolean;\n data?: unknown;\n error?: { issues: Array<{ message: string; path: PropertyKey[] }> };\n };\n return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: 'Invalid' }] };\n}\n\n/**\n * Validates params/query/body against the route's schema. On success the parsed\n * output replaces the raw input (so coercions and defaults apply); on failure\n * responds 400 with every issue across all locations.\n */\nexport function validateRequest(schema: RequestSchema): RequestHandler {\n return (req, res, next) => {\n void (async () => {\n const issues: ValidationIssue[] = [];\n const parsed: Partial<Record<Location, unknown>> = {};\n\n for (const location of LOCATIONS) {\n const validator = schema[location];\n if (!validator) continue;\n const result = await run(validator, req[location]);\n if (result.issues) {\n for (const issue of result.issues) {\n issues.push({ location, path: pathToString(issue.path), message: issue.message });\n }\n } else {\n parsed[location] = result.value;\n }\n }\n\n if (issues.length > 0) {\n res.status(400).json({ error: 'Validation failed', statusCode: 400, issues });\n return;\n }\n\n for (const location of LOCATIONS) {\n if (location in parsed) {\n // req.query is a getter in some Express setups — define rather than assign.\n Object.defineProperty(req as Request, location, {\n value: parsed[location],\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n next();\n })().catch(next);\n };\n}\n","import type { IRouter, RequestHandler } from 'express';\nimport type { MountedRoute, RouteMeta, RouteEntry, RouteSchema } from '../types.js';\nimport { schemaFor, validateRequest } from './validate.js';\n\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const;\ntype HttpMethod = (typeof HTTP_METHODS)[number];\n\nfunction asyncWrap(handler: RequestHandler): RequestHandler {\n return (req, res, next) => {\n Promise.resolve(handler(req, res, next)).catch(next);\n };\n}\n\n/**\n * For RegExp-mounted (catch-all) routes, Express exposes captures as params[0..n].\n * Rename them to the segment names from the file path; catch-alls become string\n * arrays (`[...slug]` → `['a', 'b']`), absent optional segments become undefined.\n */\nfunction namedParams(route: RouteEntry): RequestHandler {\n const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\\*/g)].map((m) => m[1]!));\n return (req, _res, next) => {\n const positional = req.params as Record<string, string | undefined>;\n const named: Record<string, unknown> = {};\n route.params.forEach((name, i) => {\n const value = positional[String(i)];\n if (value === undefined || value === '') {\n named[name] = catchAlls.has(name) ? [] : undefined;\n } else if (catchAlls.has(name)) {\n named[name] = value.split('/').filter(Boolean).map(decodeURIComponent);\n } else {\n named[name] = decodeURIComponent(value);\n }\n });\n req.params = named as typeof req.params;\n next();\n };\n}\n\nexport async function mountRoutes(app: IRouter, routes: RouteEntry[]): Promise<MountedRoute[]> {\n const mounted: MountedRoute[] = [];\n\n for (const route of routes) {\n const mod = (await import(route.filePath)) as Record<string, unknown>;\n const routeMiddlewares: RequestHandler[] = Array.isArray(mod['middlewares'])\n ? (mod['middlewares'] as RequestHandler[])\n : [];\n\n const raw = mod['meta'];\n const meta: RouteMeta | undefined =\n raw != null && typeof raw === 'object' && !Array.isArray(raw)\n ? (raw as RouteMeta)\n : undefined;\n\n const schema =\n mod['schema'] != null && typeof mod['schema'] === 'object'\n ? (mod['schema'] as RouteSchema)\n : undefined;\n\n const routePath = route.pattern ?? route.urlPath;\n const paramMapper = route.pattern ? [namedParams(route)] : [];\n\n const implemented: HttpMethod[] = [];\n const unimplemented: HttpMethod[] = [];\n\n for (const method of HTTP_METHODS) {\n if (typeof mod[method] === 'function') {\n implemented.push(method);\n const methodSchema = schemaFor(schema, method);\n const validation = methodSchema ? [validateRequest(methodSchema)] : [];\n app[method.toLowerCase() as Lowercase<HttpMethod>](\n routePath,\n ...paramMapper,\n ...routeMiddlewares,\n ...validation,\n asyncWrap(mod[method] as RequestHandler),\n );\n } else {\n unimplemented.push(method);\n }\n }\n\n if (implemented.length > 0 && unimplemented.length > 0) {\n const allowHeader = implemented.join(', ');\n app.all(routePath, (req, res, next) => {\n if ((unimplemented as string[]).includes(req.method)) {\n res.set('Allow', allowHeader).status(405).json({ error: 'Method Not Allowed' });\n } else {\n next();\n }\n });\n }\n\n mounted.push({ ...route, methods: implemented, ...(meta !== undefined && { meta }) });\n }\n\n return mounted;\n}\n\nexport { asyncWrap };\n","import cluster from 'node:cluster';\nimport { getLogger } from '../logger.js';\n\ninterface ClusterOptions {\n workers?: number;\n onWorkerReady?: ((id: number) => void) | undefined;\n onWorkerCrash?: ((id: number, code: number) => void) | undefined;\n}\n\nlet isShuttingDown = false;\n\n/**\n * Returns the number of currently alive (not yet exited) cluster workers.\n * Returns `0` when running in single-process mode.\n */\nexport function workerCount(): number {\n return Object.keys(cluster.workers ?? {}).length;\n}\n\nexport function shutdownMaster(): void {\n isShuttingDown = true;\n getLogger().info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers…`);\n if (workerCount() === 0) process.exit(0);\n // Orchestrators (docker stop, k8s) signal only PID 1 — the primary — so forward the\n // signal; each worker's gracefulShutdown drains its server and exits on its own.\n for (const worker of Object.values(cluster.workers ?? {})) {\n worker?.process.kill('SIGTERM');\n }\n}\n\nexport function runMaster(options: ClusterOptions = {}): void {\n const count = options.workers ?? 1;\n\n getLogger().info(`Primary ${process.pid} starting ${count} workers`);\n\n for (let i = 0; i < count; i++) {\n cluster.fork();\n }\n\n cluster.on('online', (worker) => {\n options.onWorkerReady?.(worker.id);\n });\n\n cluster.on('exit', (worker, code, signal) => {\n const exitCode = code ?? (signal ? -1 : 0);\n if (isShuttingDown) {\n getLogger().info(`Worker ${worker.id} gracefully exited`);\n if (workerCount() === 0) {\n getLogger().info('All workers exited. Primary exiting.');\n process.exit(0);\n }\n return;\n }\n\n getLogger().warn(`Worker ${worker.id} exited (code=${exitCode}), respawning…`);\n options.onWorkerCrash?.(worker.id, exitCode);\n cluster.fork();\n });\n}\n\nexport { cluster };\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { registerTask } from './index.js';\nimport { getLogger } from '../logger.js';\nimport type { TaskDefinition } from '../types.js';\n\nexport async function scanTasks(tasksDir: string): Promise<void> {\n if (!fs.existsSync(tasksDir)) return;\n\n const files = fs.readdirSync(tasksDir).filter((f) => /\\.(ts|js|mts|mjs)$/.test(f));\n\n for (const file of files) {\n const filePath = path.join(tasksDir, file);\n const taskName = path.basename(file, path.extname(file));\n\n try {\n const mod = (await import(filePath)) as Record<string, unknown>;\n const def = mod['default'] as TaskDefinition | undefined;\n\n if (!def || typeof def.handler !== 'function') {\n getLogger().warn(`Task file ${file} has no valid default export — skipping`);\n continue;\n }\n\n registerTask(taskName, { ...def, filePath });\n getLogger().debug(`Registered task: ${taskName}`);\n } catch (err) {\n getLogger().warn({ err }, `Failed to load task ${file}`);\n }\n }\n}\n","import type { MountedRoute } from './types.js';\n\nconst HTTP_STATUS: Record<number, string> = {\n 200: 'OK',\n 201: 'Created',\n 202: 'Accepted',\n 204: 'No Content',\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 409: 'Conflict',\n 422: 'Unprocessable Entity',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n};\n\nexport function generateDashboard(\n routes: MountedRoute[],\n basePath: string,\n port: number,\n projectName: string,\n projectVersion: string,\n): string {\n const safeRoutes = JSON.stringify(\n routes.map((r) => ({\n urlPath: r.urlPath,\n methods: r.methods,\n params: r.params,\n meta: r.meta ?? null,\n })),\n ).replace(/<\\/script>/gi, '<\\\\/script>');\n const safeHttpStatus = JSON.stringify(HTTP_STATUS);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${projectName} — API Reference</title>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin />\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap\" rel=\"stylesheet\" />\n <style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n :root {\n --bg: #080b0f;\n --bg-card: #0d1117;\n --bg-raised: #111820;\n --border: #1e2832;\n --border-lit: #263040;\n --text: #e2e8f0;\n --text-dim: #64748b;\n --text-muted: #334155;\n --accent: #F0A030;\n --accent-dim: rgba(240,160,48,.12);\n --accent-glow: rgba(240,160,48,.22);\n --purple: #a78bfa;\n --blue: #60a5fa;\n --orange: #fb923c;\n --green: #7AAE8E;\n --radius: 10px;\n --radius-lg: 16px;\n --font-mono: 'JetBrains Mono', monospace;\n --font-sans: 'Inter', sans-serif;\n }\n html { scroll-behavior: smooth; }\n body {\n background: var(--bg); color: var(--text);\n font-family: var(--font-sans); font-size: 16px;\n line-height: 1.6; -webkit-font-smoothing: antialiased;\n position: relative;\n }\n body::before {\n content: ''; position: fixed; inset: 0; z-index: 0;\n background-image:\n linear-gradient(var(--border) 1px, transparent 1px),\n linear-gradient(90deg, var(--border) 1px, transparent 1px);\n background-size: 60px 60px; opacity: .28; pointer-events: none;\n }\n section, footer, .page-hero, .docs-layout { position: relative; z-index: 1; }\n a { text-decoration: none; color: inherit; }\n em { font-style: italic; }\n code {\n font-family: var(--font-mono); font-size: .85em;\n background: var(--bg-raised); border: 1px solid var(--border);\n border-radius: 4px; padding: 1px 6px; color: var(--accent);\n }\n .container { max-width: 1140px; margin: 0 auto; padding: 0 24px; }\n ::-webkit-scrollbar { width: 6px; }\n ::-webkit-scrollbar-track { background: var(--bg); }\n ::-webkit-scrollbar-thumb { background: var(--border-lit); border-radius: 3px; }\n\n /* ── PAGE HERO ── */\n .page-hero {\n padding: 48px 0 56px; border-bottom: 1px solid var(--border);\n }\n .page-hero .hero-glow {\n position: absolute; top: -40px; left: 10%; width: 500px; height: 350px;\n background: radial-gradient(ellipse, rgba(240,160,48,.1) 0%, transparent 68%);\n pointer-events: none;\n }\n .page-title {\n font-size: clamp(2rem, 5vw, 3.4rem); font-weight: 800;\n line-height: 1.1; letter-spacing: -.02em; margin-bottom: 24px;\n display: flex; align-items: baseline; gap: 16px; flex-wrap: wrap;\n }\n .project-version {\n font-family: var(--font-mono); font-size: clamp(.85rem, 2vw, 1.1rem);\n font-weight: 500; color: var(--accent);\n background: var(--accent-dim); border: 1px solid rgba(240,160,48,.3);\n border-radius: 6px; padding: 2px 10px; letter-spacing: .5px;\n }\n .hero-meta { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 40px; }\n .base-url-pill {\n display: flex; align-items: center; gap: 8px;\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: 7px; padding: 8px 14px;\n }\n .base-url-label { font-size: .72rem; font-family: var(--font-mono);\n color: var(--text-muted); text-transform: uppercase; letter-spacing: .5px; }\n .base-url-val { font-family: var(--font-mono); font-size: .8rem; color: var(--accent); }\n .count-pill {\n font-family: var(--font-mono); font-size: .72rem; color: var(--text-dim);\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: 7px; padding: 8px 14px;\n }\n\n /* ── TOOLBAR ── */\n .toolbar {\n display: flex; align-items: center; gap: 12px; flex-wrap: wrap;\n }\n .method-filters { display: flex; gap: 4px; flex-wrap: wrap; }\n .filter-btn {\n background: var(--bg-card); border: 1px solid var(--border);\n color: var(--text-dim); font-family: var(--font-mono);\n font-size: .72rem; font-weight: 600; letter-spacing: .5px;\n padding: 6px 12px; border-radius: 6px; cursor: pointer;\n transition: all .15s;\n }\n .filter-btn:hover { border-color: var(--border-lit); color: var(--text); }\n .filter-btn.active { background: var(--accent); color: #0d0d1a; border-color: var(--accent); }\n .filter-btn[data-method=\"GET\"].active { background: rgba(96,165,250,.18); color: #60a5fa; border-color: rgba(96,165,250,.4); }\n .filter-btn[data-method=\"POST\"].active { background: rgba(122,174,142,.18); color: #7AAE8E; border-color: rgba(122,174,142,.4); }\n .filter-btn[data-method=\"PUT\"].active { background: rgba(240,160,48,.18); color: #F0A030; border-color: rgba(240,160,48,.4); }\n .filter-btn[data-method=\"PATCH\"].active { background: rgba(251,191,36,.18); color: #fbbf24; border-color: rgba(251,191,36,.4); }\n .filter-btn[data-method=\"DELETE\"].active { background: rgba(248,113,113,.18); color: #f87171; border-color: rgba(248,113,113,.4); }\n .filter-btn[data-method=\"HEAD\"].active { background: rgba(167,139,250,.18); color: #a78bfa; border-color: rgba(167,139,250,.4); }\n .search-wrap { margin-left: auto; }\n .search-input {\n background: var(--bg-card); border: 1px solid var(--border);\n color: var(--text); font-family: var(--font-sans); font-size: .85rem;\n padding: 7px 14px; border-radius: 7px; width: 240px;\n outline: none; transition: border-color .2s;\n }\n .search-input::placeholder { color: var(--text-muted); }\n .search-input:focus { border-color: var(--border-lit); }\n\n /* ── DOCS LAYOUT ── */\n .docs-layout {\n display: grid; grid-template-columns: 260px 1fr;\n gap: 48px; padding: 52px 0 80px; max-width: 1140px;\n margin: 0 auto; padding-left: 24px; padding-right: 24px;\n align-items: start;\n }\n\n /* ── SIDEBAR ── */\n .docs-sidebar {\n position: sticky; top: 24px;\n max-height: calc(100vh - 48px);\n overflow-y: auto;\n overflow-x: hidden;\n scrollbar-width: none;\n padding-right: 4px;\n }\n .docs-sidebar::-webkit-scrollbar { display: none; }\n .sidebar-section { margin-bottom: 28px; }\n .sidebar-label {\n font-family: var(--font-mono); font-size: .68rem; font-weight: 600;\n color: var(--text-muted); letter-spacing: 1.2px; text-transform: uppercase;\n margin-bottom: 8px; padding: 0 4px;\n }\n .sidebar-link {\n display: flex; align-items: center; gap: 8px;\n padding: 7px 10px; border-radius: 6px;\n border-left: 2px solid transparent;\n font-size: .82rem; color: var(--text-dim); cursor: pointer;\n transition: background .15s, color .15s, border-color .15s;\n overflow: hidden; white-space: nowrap;\n }\n .sidebar-link:hover { background: var(--bg-raised); color: var(--text); }\n .sidebar-link.active { color: var(--accent); border-left-color: var(--accent); background: var(--accent-dim); }\n .sidebar-method-dot {\n width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0;\n }\n .sidebar-path { font-family: var(--font-mono); font-size: .72rem; }\n\n /* ── ENDPOINT CARDS ── */\n .endpoint-card {\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: var(--radius-lg); margin-bottom: 20px;\n overflow: hidden; transition: border-color .2s;\n animation: fadeUp .45s ease both;\n }\n .endpoint-card:hover { border-color: var(--border-lit); }\n @keyframes fadeUp {\n from { opacity: 0; transform: translateY(16px); }\n to { opacity: 1; transform: translateY(0); }\n }\n @media (prefers-reduced-motion: reduce) {\n .endpoint-card { animation: none; }\n }\n .endpoint-header {\n display: flex; align-items: center; gap: 14px;\n padding: 20px 24px 18px; border-bottom: 1px solid var(--border);\n flex-wrap: wrap;\n }\n .method-badges { display: flex; gap: 6px; flex-wrap: wrap; }\n .method-badge {\n font-family: var(--font-mono); font-size: .7rem; font-weight: 600;\n letter-spacing: .8px; padding: 4px 10px; border-radius: 5px;\n border: 1px solid; text-transform: uppercase;\n }\n .endpoint-path {\n font-family: var(--font-mono); font-size: .9rem; color: var(--text);\n background: none; border: none; padding: 0;\n word-break: break-all;\n }\n .endpoint-body { padding: 6px 24px 24px; }\n .endpoint-desc { font-size: .9rem; color: var(--text-dim); line-height: 1.7; margin-bottom: 20px; }\n\n /* ── PER-METHOD DOC BLOCKS ── */\n .method-block { padding-top: 20px; }\n .method-block + .method-block { margin-top: 4px; border-top: 1px solid var(--border); }\n .method-block-header { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }\n .method-block-header .method-badge { font-size: .68rem; }\n .method-block-empty { font-size: .82rem; color: var(--text-muted); }\n\n /* ── CODE BLOCKS ── */\n .example-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }\n .code-block-wrap {\n background: var(--bg-raised); border: 1px solid var(--border);\n border-radius: var(--radius); overflow: hidden;\n }\n .code-bar {\n display: flex; align-items: center; gap: 6px;\n padding: 9px 14px; border-bottom: 1px solid var(--border);\n background: var(--bg-card);\n }\n .dot { width: 11px; height: 11px; border-radius: 50%; }\n .dot-r { background: #ff5f57; }\n .dot-y { background: #febc2e; }\n .dot-g { background: #28c840; }\n .code-label { font-family: var(--font-mono); font-size: .68rem; color: var(--text-dim); margin-left: 4px; }\n pre.code-pre {\n font-family: var(--font-mono); font-size: .78rem; line-height: 1.7;\n padding: 16px 18px; overflow-x: auto; tab-size: 2; white-space: pre;\n }\n .c-dim { color: var(--text-muted); }\n .c-green { color: #7AAE8E; }\n .c-blue { color: #60a5fa; }\n .c-orange { color: #fb923c; }\n .c-purple { color: #a78bfa; }\n .c-accent { color: var(--accent); }\n .status-2xx { color: #7AAE8E; }\n .status-4xx { color: #f87171; }\n .status-5xx { color: #fb923c; }\n\n /* ── EMPTY STATE ── */\n .empty-state {\n text-align: center; padding: 80px 24px;\n color: var(--text-muted); font-size: .9rem;\n }\n\n /* ── RESPONSIVE ── */\n @media (max-width: 900px) {\n .docs-layout { grid-template-columns: 1fr; }\n .docs-sidebar { position: static; max-height: none; overflow-y: visible; padding-right: 0; }\n .example-grid { grid-template-columns: 1fr; }\n .search-wrap { margin-left: 0; width: 100%; }\n .search-input { width: 100%; }\n }\n @media (max-width: 600px) {\n .page-hero { padding: 32px 0 32px; }\n .page-title { font-size: 2rem; }\n }\n </style>\n</head>\n<body>\n\n <div class=\"page-hero\">\n <div class=\"hero-glow\"></div>\n <div class=\"container\">\n <h1 class=\"page-title\">${projectName}${projectVersion ? `<span class=\"project-version\">v${projectVersion}</span>` : ''}</h1>\n <div class=\"hero-meta\">\n <div class=\"base-url-pill\">\n <span class=\"base-url-label\">Base</span>\n <span class=\"base-url-val\">http://localhost:${port}${basePath}</span>\n </div>\n <div class=\"count-pill\" id=\"countPill\"></div>\n </div>\n <div class=\"toolbar\">\n <div class=\"method-filters\" id=\"methodFilters\">\n <button class=\"filter-btn active\" data-method=\"ALL\">ALL</button>\n </div>\n <div class=\"search-wrap\">\n <input type=\"text\" id=\"searchInput\" class=\"search-input\" placeholder=\"Search endpoints…\" />\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"docs-layout\">\n <aside class=\"docs-sidebar\" id=\"sidebar\"></aside>\n <main id=\"endpoints\"></main>\n </div>\n\n <script>\n const ROUTES = ${safeRoutes};\n const BASE_PATH = ${JSON.stringify(basePath)};\n const HTTP_STATUS = ${safeHttpStatus};\n\n const METHOD_STYLE = {\n GET: { bg: 'rgba(96,165,250,.14)', color: '#60a5fa', border: 'rgba(96,165,250,.35)' },\n POST: { bg: 'rgba(122,174,142,.14)', color: '#7AAE8E', border: 'rgba(122,174,142,.35)' },\n PUT: { bg: 'rgba(240,160,48,.14)', color: '#F0A030', border: 'rgba(240,160,48,.35)' },\n PATCH: { bg: 'rgba(251,191,36,.14)', color: '#fbbf24', border: 'rgba(251,191,36,.35)' },\n DELETE: { bg: 'rgba(248,113,113,.14)', color: '#f87171', border: 'rgba(248,113,113,.35)' },\n HEAD: { bg: 'rgba(167,139,250,.14)', color: '#a78bfa', border: 'rgba(167,139,250,.35)' },\n OPTIONS: { bg: 'rgba(148,163,184,.14)', color: '#94a3b8', border: 'rgba(148,163,184,.35)' },\n };\n\n function esc(s) {\n return String(s)\n .replace(/&/g,'&').replace(/</g,'<')\n .replace(/>/g,'>').replace(/\"/g,'"');\n }\n\n function methodBadge(m) {\n const s = METHOD_STYLE[m] || METHOD_STYLE.GET;\n return '<span class=\"method-badge\" style=\"background:' + s.bg + ';color:' + s.color + ';border-color:' + s.border + '\">' + m + '</span>';\n }\n\n function joinPath(base, p) {\n return (base.replace(/\\\\/+$/, '') + p) || '/';\n }\n\n function sidebarDot(method) {\n const s = METHOD_STYLE[method] || METHOD_STYLE.GET;\n return '<span class=\"sidebar-method-dot\" style=\"background:' + s.color + '\"></span>';\n }\n\n function statusClass(code) {\n if (code >= 200 && code < 300) return 'status-2xx';\n if (code >= 400 && code < 500) return 'status-4xx';\n if (code >= 500) return 'status-5xx';\n return '';\n }\n\n function renderSchema(val, indent) {\n const pad = ' '.repeat(indent || 0);\n if (val === null) return '<span class=\"c-dim\">null</span>';\n if (typeof val === 'string') {\n const isDate = /^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}/.test(val);\n return isDate ? '<span class=\"c-green\">Date</span>' : '<span class=\"c-purple\">String</span>';\n }\n if (typeof val === 'number') return '<span class=\"c-orange\">Number</span>';\n if (typeof val === 'boolean') return '<span class=\"c-purple\">Boolean</span>';\n if (Array.isArray(val)) {\n if (!val.length) return '[]';\n return '[\\\\n' + pad + ' ' + renderSchema(val[0], (indent || 0) + 1) + '\\\\n' + pad + ']';\n }\n if (typeof val === 'object') {\n const keys = Object.keys(val);\n if (!keys.length) return '{}';\n const inner = keys.map(function(k) {\n return pad + ' <span class=\"c-blue\">"' + esc(k) + '"</span>: ' + renderSchema(val[k], (indent || 0) + 1);\n }).join(',\\\\n');\n return '{\\\\n' + inner + '\\\\n' + pad + '}';\n }\n return esc(String(val));\n }\n\n function codeBlock(label, content) {\n return '<div class=\"code-block-wrap\">' +\n '<div class=\"code-bar\">' +\n '<span class=\"dot dot-r\"></span>' +\n '<span class=\"dot dot-y\"></span>' +\n '<span class=\"dot dot-g\"></span>' +\n '<span class=\"code-label\">' + esc(label) + '</span>' +\n '</div>' +\n '<pre class=\"code-pre\">' + content + '</pre>' +\n '</div>';\n }\n\n function buildRequestContent(route, method, example) {\n const req = example || {};\n let path = joinPath(BASE_PATH, route.urlPath);\n if (req.params) {\n for (const [k, v] of Object.entries(req.params)) {\n path = path.replace(':' + k, String(v));\n }\n }\n if (req.query && Object.keys(req.query).length) {\n path += '?' + new URLSearchParams(req.query).toString();\n }\n let lines = '<span class=\"c-accent\">' + esc(method) + '</span> <span class=\"c-blue\">' + esc(path) + '</span>';\n const headers = { ...(req.headers || {}) };\n if (req.body !== undefined && !headers['Content-Type']) {\n headers['Content-Type'] = 'application/json';\n }\n if (Object.keys(headers).length) {\n lines += '\\\\n' + Object.entries(headers)\n .map(([k, v]) => '<span class=\"c-dim\">' + esc(k) + ':</span> ' + esc(String(v)))\n .join('\\\\n');\n }\n if (req.body !== undefined) {\n lines += '\\\\n\\\\n' + renderSchema(req.body, 0);\n }\n return lines;\n }\n\n function buildResponseContent(example) {\n const resp = example || {};\n const code = resp.status || 200;\n const text = HTTP_STATUS[code] || 'OK';\n const cls = statusClass(code);\n let lines = 'HTTP/1.1 <span class=\"' + cls + '\">' + code + ' ' + esc(text) + '</span>';\n if (resp.body !== undefined) {\n lines += '\\\\n<span class=\"c-dim\">Content-Type:</span> application/json\\\\n\\\\n';\n lines += renderSchema(resp.body, 0);\n }\n return lines;\n }\n\n function renderMethodBlock(route, method) {\n const methodMeta = route.meta ? route.meta[method] : null;\n const header = '<div class=\"method-block-header\">' + methodBadge(method) + '</div>';\n\n if (!methodMeta) {\n return '<div class=\"method-block\" data-method=\"' + esc(method) + '\">' + header +\n '<p class=\"method-block-empty\">No documentation provided for this method.</p></div>';\n }\n\n const desc = methodMeta.description\n ? '<p class=\"endpoint-desc\">' + esc(methodMeta.description) + '</p>'\n : '';\n const reqHtml = methodMeta.request !== undefined\n ? codeBlock('request', buildRequestContent(route, method, methodMeta.request))\n : '';\n const respHtml = methodMeta.response !== undefined\n ? codeBlock('response', buildResponseContent(methodMeta.response))\n : '';\n const examples = reqHtml || respHtml\n ? '<div class=\"example-grid\">' + reqHtml + respHtml + '</div>'\n : '';\n\n return '<div class=\"method-block\" data-method=\"' + esc(method) + '\">' + header + desc + examples + '</div>';\n }\n\n function renderCard(route, index) {\n const id = 'ep-' + index;\n const fullPath = joinPath(BASE_PATH, route.urlPath);\n const badges = route.methods.map(methodBadge).join('');\n const body = route.methods.map(function(m) { return renderMethodBlock(route, m); }).join('');\n const delay = (index * 0.06).toFixed(2) + 's';\n return '<div class=\"endpoint-card\" id=\"' + id + '\" data-methods=\"' + route.methods.join(',') + '\" data-path=\"' + esc(fullPath) + '\" style=\"animation-delay:' + delay + '\">' +\n '<div class=\"endpoint-header\">' +\n '<div class=\"method-badges\">' + badges + '</div>' +\n '<code class=\"endpoint-path\">' + esc(fullPath) + '</code>' +\n '</div>' +\n '<div class=\"endpoint-body\">' + body + '</div>' +\n '</div>';\n }\n\n function buildMethodFilters() {\n const allMethods = [...new Set(ROUTES.flatMap(r => r.methods))].sort();\n const filtersEl = document.getElementById('methodFilters');\n allMethods.forEach(m => {\n const btn = document.createElement('button');\n btn.className = 'filter-btn';\n btn.dataset.method = m;\n btn.textContent = m;\n filtersEl.appendChild(btn);\n });\n }\n\n function buildSidebar(routes) {\n const sidebar = document.getElementById('sidebar');\n if (!routes.length) { sidebar.innerHTML = ''; return; }\n\n const label = document.createElement('div');\n label.className = 'sidebar-label';\n label.textContent = 'Endpoints';\n sidebar.appendChild(label);\n\n routes.forEach((route, i) => {\n const link = document.createElement('div');\n link.className = 'sidebar-link';\n link.dataset.target = 'ep-' + ROUTES.indexOf(route);\n link.innerHTML = sidebarDot(route.methods[0] || 'GET') +\n '<span class=\"sidebar-path\">' + esc(route.urlPath || '/') + '</span>';\n link.addEventListener('click', () => {\n const target = document.getElementById(link.dataset.target);\n if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });\n });\n sidebar.appendChild(link);\n });\n }\n\n let activeFilter = 'ALL';\n let searchQuery = '';\n\n function applyFilters() {\n const cards = document.querySelectorAll('.endpoint-card');\n let visible = 0;\n cards.forEach(card => {\n const methods = card.dataset.methods.split(',');\n const path = card.dataset.path || '';\n const matchMethod = activeFilter === 'ALL' || methods.includes(activeFilter);\n const matchSearch = !searchQuery || path.toLowerCase().includes(searchQuery);\n const show = matchMethod && matchSearch;\n card.style.display = show ? '' : 'none';\n if (show) visible++;\n });\n document.getElementById('empty-state').style.display = visible ? 'none' : 'block';\n\n // Sync sidebar visibility\n document.querySelectorAll('.sidebar-link').forEach(link => {\n const targetId = link.dataset.target;\n const targetCard = document.getElementById(targetId);\n link.style.display = targetCard && targetCard.style.display !== 'none' ? '' : 'none';\n });\n }\n\n function init() {\n const count = ROUTES.length;\n document.getElementById('countPill').textContent = count + ' endpoint' + (count !== 1 ? 's' : '');\n\n buildMethodFilters();\n\n const container = document.getElementById('endpoints');\n container.innerHTML = ROUTES.map((r, i) => renderCard(r, i)).join('');\n\n // Add empty state after cards\n const emptyEl = document.createElement('div');\n emptyEl.id = 'empty-state';\n emptyEl.className = 'empty-state';\n emptyEl.style.display = 'none';\n emptyEl.innerHTML = '<p>No endpoints match your filter.</p>';\n container.after(emptyEl);\n\n buildSidebar(ROUTES);\n\n // Method filter clicks\n document.getElementById('methodFilters').addEventListener('click', e => {\n const btn = e.target.closest('.filter-btn');\n if (!btn) return;\n document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));\n btn.classList.add('active');\n activeFilter = btn.dataset.method;\n applyFilters();\n });\n\n // Search\n document.getElementById('searchInput').addEventListener('input', e => {\n searchQuery = e.target.value.trim().toLowerCase();\n applyFilters();\n });\n\n // Scroll spy for sidebar\n const cardEls = document.querySelectorAll('.endpoint-card');\n const sidebarLinks = document.querySelectorAll('.sidebar-link');\n const observer = new IntersectionObserver(entries => {\n entries.forEach(entry => {\n if (entry.isIntersecting) {\n const id = entry.target.id;\n sidebarLinks.forEach(l => l.classList.toggle('active', l.dataset.target === id));\n const sidebar = document.getElementById('sidebar');\n const activeLink = sidebar && sidebar.querySelector('.sidebar-link.active');\n if (sidebar && activeLink) {\n const linkTop = activeLink.getBoundingClientRect().top - sidebar.getBoundingClientRect().top + sidebar.scrollTop;\n sidebar.scrollTo({ top: linkTop, behavior: 'smooth' });\n }\n }\n });\n }, { rootMargin: '-80px 0px -60% 0px' });\n cardEls.forEach(el => observer.observe(el));\n\n }\n\n try {\n init();\n } catch (e) {\n document.body.insertAdjacentHTML('afterbegin',\n '<div style=\"position:fixed;top:60px;left:0;right:0;z-index:9999;background:#7f1d1d;color:#fca5a5;padding:16px 24px;font-family:monospace;font-size:13px;border-bottom:1px solid #ef4444\">' +\n '<strong>Dashboard JS error:</strong> ' + (e && e.message ? e.message : String(e)) +\n (e && e.stack ? '<pre style=\"margin-top:8px;white-space:pre-wrap\">' + e.stack + '</pre>' : '') +\n '</div>'\n );\n }\n </script>\n</body>\n</html>`;\n}\n","import type { Request, RequestHandler } from 'express';\nimport { cache } from './index.js';\nimport { getCurrentUser } from '../context.js';\n\nexport interface CacheResponseOptions {\n /** Seconds to keep a response. */\n ttl: number;\n /**\n * Cache per authenticated user (keyed by the JWT's `sub`/`id`). Put `requireAuth`\n * before this middleware. Without it, a response is shared by everyone hitting the URL.\n */\n perUser?: boolean;\n /** Custom cache key. Default: the request's original URL (path + query). */\n key?: (req: Request) => string;\n}\n\ninterface Stored {\n status: number;\n body: unknown;\n}\n\n/** Key prefix for cached responses — `cache.clear(RESPONSE_PREFIX + '/v1/api/posts')` drops those. */\nexport const RESPONSE_PREFIX = 'res:';\n\n/**\n * Caches successful (200) JSON responses of GET/HEAD requests. Adds `X-Cache: HIT|MISS`.\n *\n * @example\n * export const middlewares = [cacheResponse(60)];\n * export const middlewares = [requireAuth, cacheResponse({ ttl: 30, perUser: true })];\n */\nexport function cacheResponse(options: number | CacheResponseOptions): RequestHandler {\n const opts: CacheResponseOptions = typeof options === 'number' ? { ttl: options } : options;\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') return next();\n\n let scope = '';\n if (opts.perUser) {\n const user = getCurrentUser();\n const id = user?.['sub'] ?? user?.['id'];\n // Never fall back to a shared entry for a per-user route.\n if (id === undefined) return next();\n scope = `u:${String(id)}:`;\n }\n const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);\n\n void (async () => {\n const hit = await cache.get<Stored>(key);\n if (hit) {\n res.setHeader('X-Cache', 'HIT');\n res.status(hit.status).json(hit.body);\n return;\n }\n res.setHeader('X-Cache', 'MISS');\n const json = res.json.bind(res);\n res.json = (body: unknown) => {\n if (res.statusCode === 200) void cache.set(key, { status: 200, body }, { ttl: opts.ttl });\n return json(body);\n };\n next();\n })().catch(next);\n };\n}\n","import type { RequestHandler } from 'express';\n\n/**\n * Chains multiple Express request handlers into a single handler.\n * Each handler calls the next one via its `next` callback.\n *\n * @example\n * export const GET = compose(requireAuth, rateLimiter, myHandler);\n */\nexport function compose(...handlers: RequestHandler[]): RequestHandler {\n return (req, res, next) => {\n function dispatch(i: number): void {\n if (i >= handlers.length) {\n next();\n return;\n }\n const handler = handlers[i];\n if (!handler) {\n next();\n return;\n }\n try {\n Promise.resolve(handler(req, res, () => dispatch(i + 1))).catch(next);\n } catch (err) {\n next(err);\n }\n }\n\n dispatch(0);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAOA,SAAQ;AACf,OAAO,aAAa;AACpB,OAAO,UAAU;AACjB,OAAO,kBAAkB;AACzB,OAAOC,cAAa;AACpB,OAAO,QAAQ;AACf,OAAOC,WAAU;;;ACJjB,IAAM,YAAY,CAAC,UAAU,SAAS,MAAM;AAW5C,SAAS,gBAAgB,OAAwC;AAC/D,SACE,SAAS,QACT,OAAO,UAAU,YACjB,UAAU,KAAK,CAAC,QAAQ,OAAQ,KAAiC;AAErE;AAGO,SAAS,UACd,QACA,QAC2B;AAC3B,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,WAAY,OAAmC,MAAM;AAC3D,MAAI,gBAAgB,QAAQ,EAAG,QAAO;AACtC,SAAO,gBAAgB,MAAM,IAAI,SAAS;AAC5C;AAIA,SAAS,aAAaC,OAAyB;AAC7C,MAAI,CAACA,MAAM,QAAO;AAClB,SAAOA,MACJ,IAAI,CAAC,MAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,SAAS,IAAI,EAAE,MAAM,CAAE,EAC1E,IAAI,MAAM,EACV,KAAK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,GAAG,WAAW,MAAM,SAAS,SAAS,CAAC;AAC/C,UAAQ,GAAG,UAAU,MAAM,SAAS,QAAQ,CAAC;AAC/C;","names":["fs","cluster","path","path","path","fs","cluster"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/router/validate.ts","../src/router/mount.ts","../src/cluster/index.ts","../src/tasks/scanner.ts","../src/dashboard.ts","../src/rate-limit.ts","../src/cache/response.ts","../src/compose.ts"],"sourcesContent":["import type http from 'node:http';\nimport fs from 'node:fs';\nimport express from 'express';\nimport cors from 'cors';\nimport cookieParser from 'cookie-parser';\nimport cluster from 'node:cluster';\nimport os from 'node:os';\nimport path from 'node:path';\nimport type { EFCConfig, MountedRoute } from './types.js';\nexport type {\n TableModel,\n TableRecord,\n TableCreateInput,\n TableWhere,\n TableWhereUnique,\n TableUpdateData,\n TableCreateData,\n TableUpdateInput,\n TableOrderBy,\n TableSelect,\n TableInclude,\n TableResult,\n Tables,\n TableFindManyArgs,\n TableAggregateArgs,\n TableGroupByArgs,\n TableAggregateResult,\n ScalarFilter,\n StringFilter,\n ListFilter,\n JsonFilter,\n InferTableRecord,\n} from './table-types.js';\nimport { scanDir } from './router/scan.js';\nimport { mountRoutes } from './router/mount.js';\nimport { runMaster, shutdownMaster } from './cluster/index.js';\nimport { configureAuth } from './auth/index.js';\nimport { isHttpError } from './errors.js';\nimport { connectMongo } from './db/mongo.js';\nimport { setDbClient } from './db/index.js';\nimport { setDbEngine, setAutoSync } from './db/engine.js';\nimport { checkConnectionBudget, connectPostgres } from './db/postgres.js';\nimport { runWithContext } from './context.js';\nimport { configureLogger, getLogger, requestLogger } from './logger.js';\nimport { configureQueryLog } from './db/query-log.js';\nimport { scanTasks } from './tasks/scanner.js';\nimport { initBullMQ, closeBullMQ } from './tasks/bullmq-backend.js';\nimport { initPgBoss, closePgBoss } from './tasks/pgboss-backend.js';\nimport { configureCache, closeCache } from './cache/index.js';\nimport { servePrimaryCache } from './cache/ipc.js';\nimport { generateDashboard } from './dashboard.js';\n\nfunction detectDatabase(url?: string): 'mongodb' | 'postgresql' | undefined {\n if (!url) return undefined;\n if (url.startsWith('mongodb')) return 'mongodb';\n if (url.startsWith('postgres')) return 'postgresql';\n return undefined;\n}\n\nexport async function ignite(config: EFCConfig): Promise<http.Server | undefined> {\n const {\n port: _port,\n workers,\n globalMiddlewares = [],\n onWorkerReady,\n onWorkerCrash,\n onError,\n } = config;\n\n // Resolve api/tasks dirs from convention. argv[1]-based resolution is unreliable in tsx watch\n // + cluster workers (argv[1] can point to the tsx binary instead of the user's script), so we\n // probe multiple candidates and use the first that exists on disk.\n function resolveConventionDir(name: string): string {\n const candidates: string[] = [\n ...(process.argv[1] ? [path.join(path.dirname(process.argv[1]), name)] : []),\n path.join(process.cwd(), 'src', name),\n path.join(process.cwd(), name),\n path.join(process.cwd(), 'dist', name),\n ];\n return candidates.find((c) => fs.existsSync(c)) ?? candidates[0]!;\n }\n const apiDir = resolveConventionDir('api');\n const tasksDir = resolveConventionDir('tasks');\n const basePath = config.basePath ?? '/v1/api';\n\n function readProjectMeta(): { name: string; version: string } {\n try {\n const raw = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');\n const pkg = JSON.parse(raw) as { name?: string; version?: string };\n return { name: pkg.name ?? 'API', version: pkg.version ?? '' };\n } catch {\n return { name: 'API', version: '' };\n }\n }\n\n const port = _port != null && !Number.isNaN(_port) ? _port : 3000;\n const databaseUrl = config.databaseUrl;\n const database = config.database ?? detectDatabase(databaseUrl);\n const jwtSecret = config.jwtSecret;\n const authStrategy = config.authStrategy ?? 'http-only';\n // NODE_ENV is a Node/Express-wide runtime-mode signal set by the platform, not an app\n // secret — unlike PORT/DATABASE_URL/JWT_SECRET/etc. this one is still read directly.\n const clusterEnabled = config.cluster ?? process.env['NODE_ENV'] === 'production';\n\n configureLogger(config.logging);\n // Any value but 'http-only' acts as bearer, as it always has — an app may rely on that, so\n // 0.9.x only warns (a typo of 'http-only' silently means no cookie). 1.0 makes it an error.\n if (\n !['http-only', 'bearer', 'localStorage'].includes(authStrategy) &&\n (!clusterEnabled || cluster.isPrimary) // once, not once per worker\n ) {\n getLogger().warn(\n `[EFC] Unknown authStrategy \"${String(authStrategy)}\" — treated as 'bearer'. Use 'http-only' or 'bearer'; this will be an error in 1.0.`,\n );\n }\n // HS256 with a short secret can be brute-forced offline from any token a user holds.\n if (\n jwtSecret &&\n Buffer.byteLength(jwtSecret) < 32 &&\n process.env['NODE_ENV'] === 'production' &&\n (!clusterEnabled || cluster.isPrimary)\n ) {\n getLogger().warn(\n `[EFC] jwtSecret is ${Buffer.byteLength(jwtSecret)} bytes — use at least 32 random bytes in production (openssl rand -hex 64).`,\n );\n }\n configureQueryLog(config.logging);\n\n if (clusterEnabled && cluster.isPrimary) {\n // The memory cache lives in the primary so all workers share it (cache/ipc.ts).\n if (config.cache && config.cache.backend === 'memory') {\n servePrimaryCache(config.cache.maxEntries ?? 10_000);\n }\n runMaster({\n workers: workers ?? os.cpus().length,\n ...(onWorkerReady !== undefined && { onWorkerReady }),\n ...(onWorkerCrash !== undefined && { onWorkerCrash }),\n });\n return;\n }\n\n const app = express();\n if (config.trustProxy !== undefined) app.set('trust proxy', config.trustProxy);\n // defineTable returns `bigint` for bigint columns and bigserial ids, which JSON.stringify\n // rejects; send them as strings (exact — a JS number would lose precision past 2^53).\n app.set('json replacer', (_key: string, value: unknown) =>\n typeof value === 'bigint' ? value.toString() : value,\n );\n\n // Wraps every request in its own AsyncLocalStorage context, first thing, so\n // requireAuth (below) and any downstream code — including a `$currentUser`\n // default resolved inside a mongoose `.create()` call — share the same store.\n app.use((_req, _res, next) => {\n runWithContext({}, next);\n });\n app.use(requestLogger());\n\n if (config.requestTimeout) {\n const ms = config.requestTimeout;\n app.use((_req, res, next) => {\n const timer = setTimeout(() => {\n if (!res.headersSent) res.status(408).json({ error: 'Request Timeout', statusCode: 408 });\n }, ms);\n const clear = () => clearTimeout(timer);\n res.once('finish', clear);\n res.once('close', clear);\n next();\n });\n }\n\n const corsOption = config.cors ?? true;\n if (corsOption !== false) {\n const origin =\n typeof corsOption === 'object' && corsOption.origin !== undefined ? corsOption.origin : true;\n const corsOpts = typeof corsOption === 'object' ? { ...corsOption, origin } : { origin };\n app.use(cors(corsOpts));\n }\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n app.use(cookieParser());\n\n for (const mw of globalMiddlewares) {\n app.use(mw);\n }\n\n // Pre-Flight step 1: Connect database. The engine decides what defineModel compiles to.\n if (database) setDbEngine(database);\n setAutoSync(config.autoSync ?? true);\n // Pools are per worker; one process per machine reports the machine's total.\n const poolWorkers = clusterEnabled ? (workers ?? os.cpus().length) : 1;\n const reportsPools = !clusterEnabled || cluster.worker?.id === 1;\n if (database === 'mongodb' && databaseUrl) {\n const conn = await connectMongo(databaseUrl, config.databasePool);\n setDbClient(conn as unknown as Record<string, unknown>);\n if (reportsPools) {\n const max = config.databasePool?.max ?? 100; // mongoose's maxPoolSize default\n getLogger().info(\n `MongoDB connections: up to ${poolWorkers * max} from this machine (${poolWorkers} worker(s) × maxPoolSize ${max})`,\n );\n }\n } else if (database === 'postgresql' && databaseUrl) {\n const pool = await connectPostgres(databaseUrl, config.databasePool);\n setDbClient(pool as unknown as Record<string, unknown>);\n if (reportsPools) {\n const max = config.databasePool?.max ?? 10; // node-postgres' default\n // pg-boss on the same database opens its own pool (node-postgres default 10).\n const boss =\n config.tasks && config.tasks.backend === 'pg-boss' && !config.tasks.connectionString\n ? 10\n : 0;\n const breakdown = `${poolWorkers} worker(s) × (pool ${max}${boss ? ` + pg-boss ${boss}` : ''})`;\n await checkConnectionBudget(poolWorkers * (max + boss), breakdown);\n }\n }\n\n // Pre-Flight step 1b: Cache (also the session-revocation store requireAuth consults)\n if (config.cache) {\n await configureCache(config.cache);\n }\n\n // Pre-Flight step 2: Configure auth\n if (jwtSecret) {\n configureAuth({\n secret: jwtSecret,\n strategy: authStrategy,\n expiresIn: config.jwtExpiresIn ?? '7d',\n ...(config.cookieDomain !== undefined && { cookieDomain: config.cookieDomain }),\n });\n }\n\n // Pre-Flight step 3: Scan and register tasks\n if (tasksDir) {\n await scanTasks(tasksDir);\n }\n\n // Pre-Flight step 4: Start task queue backend\n if (config.tasks) {\n if (config.tasks.backend === 'bullmq') {\n await initBullMQ({\n redisUrl: config.tasks.redisUrl ?? 'redis://localhost:6379',\n concurrency: config.tasks.concurrency ?? 5,\n enqueueTimeout: config.tasks.enqueueTimeout ?? 5000,\n queue: config.tasks.queue ?? 'efc',\n });\n } else if (config.tasks.backend === 'pg-boss') {\n const connectionString = config.tasks.connectionString ?? databaseUrl;\n if (!connectionString) {\n throw new Error(\n '[EFC] tasks.backend \"pg-boss\" needs tasks.connectionString or databaseUrl',\n );\n }\n await initPgBoss({\n connectionString,\n concurrency: config.tasks.concurrency ?? 5,\n enqueueTimeout: config.tasks.enqueueTimeout ?? 5000,\n queue: config.tasks.queue ?? 'efc',\n ...(config.tasks.schema !== undefined && { schema: config.tasks.schema }),\n });\n }\n }\n\n // Pre-Flight step 5: Scan routes and mount\n const routes = scanDir(apiDir);\n const apiRouter = express.Router();\n const mounted: MountedRoute[] = await mountRoutes(apiRouter, routes);\n app.use(basePath, apiRouter);\n\n if (config.dashboard !== false && process.env['NODE_ENV'] === 'development') {\n app.get('/', (_req, res) => {\n const { name, version } = readProjectMeta();\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.send(generateDashboard(mounted, basePath, port, name, version));\n });\n }\n\n if (onError) {\n app.use(onError);\n } else {\n app.use(\n (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {\n // e.g. a handler that kept going after requestTimeout already answered 408.\n if (res.headersSent) {\n getLogger().warn({ err }, 'Error after the response was sent');\n return;\n }\n // isHttpError() covers the common case, but errors can also arrive as plain\n // objects with a numeric statusCode (e.g. thrown across a module boundary, or\n // duck-typed by user code) — fall back to that shape before giving up to 500.\n // Only 4xx: a library's 5xx message can describe internals (hosts, SQL, paths).\n const status = (err as { statusCode?: unknown } | null)?.statusCode;\n const duckTyped =\n err instanceof Error && typeof status === 'number' && status >= 400 && status < 500\n ? (err as Error & { statusCode: number })\n : null;\n\n if (isHttpError(err)) {\n // ModelValidationError carries per-field issues; surface them like route validation does.\n const issues = (err as { issues?: unknown }).issues;\n res.status(err.statusCode).json({\n error: err.message,\n statusCode: err.statusCode,\n ...(issues !== undefined && { issues }),\n });\n } else if (duckTyped) {\n res\n .status(duckTyped.statusCode)\n .json({ error: duckTyped.message, statusCode: duckTyped.statusCode });\n } else {\n getLogger().error({ err }, 'Unhandled error');\n res.status(500).json({ error: 'Internal Server Error', statusCode: 500 });\n }\n },\n );\n }\n\n return new Promise<http.Server>((resolve, reject) => {\n const server = app.listen(port);\n\n server.once('listening', () => {\n const wid = (cluster.worker as { id: number } | undefined)?.id ?? 'primary';\n const addr = server.address() as { port: number } | null;\n getLogger().info(`Worker ${wid} listening on :${addr?.port ?? port}`);\n resolve(server);\n });\n\n server.once('error', reject);\n });\n}\n\nexport function gracefulShutdown(server: http.Server | undefined, timeoutMs = 10_000): void {\n let shuttingDown = false;\n const shutdown = (signal: string) => {\n // A worker can get the signal twice (process-group Ctrl+C plus the primary's\n // forward); the default handler for a repeat would kill it mid-drain.\n if (shuttingDown) return;\n shuttingDown = true;\n getLogger().info(`${signal} received — closing server gracefully…`);\n if (server) {\n server.closeIdleConnections();\n server.close(() => {\n getLogger().info('Server closed');\n // Let in-flight task jobs finish before exiting; the timeout below still caps it.\n Promise.all([closeBullMQ(), closePgBoss(), closeCache()])\n .catch((err: unknown) => getLogger().error({ err }, 'Task backend close failed'))\n .finally(() => process.exit(0));\n });\n setTimeout(() => {\n getLogger().error('Forced exit after timeout');\n process.exit(1);\n }, timeoutMs).unref();\n } else {\n shutdownMaster();\n // Workers get the same budget plus a margin before the primary gives up on them.\n setTimeout(() => {\n getLogger().error('Workers did not exit in time — forcing primary exit');\n process.exit(1);\n }, timeoutMs + 2_000).unref();\n }\n };\n process.on('SIGTERM', () => shutdown('SIGTERM'));\n process.on('SIGINT', () => shutdown('SIGINT'));\n}\n\nexport { HttpError, isHttpError } from './errors.js';\nexport { logger, getLogger } from './logger.js';\nexport { cache } from './cache/index.js';\nexport { rateLimit } from './rate-limit.js';\nexport type { RateLimitOptions } from './rate-limit.js';\nexport { cacheResponse } from './cache/response.js';\nexport { compose } from './compose.js';\nexport {\n db,\n setDbClient,\n getDbClient,\n defineModel,\n defineTable,\n defineCollection,\n} from './db/index.js';\nexport type {\n CollectionModel,\n CollectionOptions,\n CollectionFilter,\n CollectionUpdate,\n CollectionFindOptions,\n CollectionWriteResult,\n CollectionBulkResult,\n CollectionBulkOp,\n CollectionChange,\n CollectionChangeStream,\n} from './db/collection-model.js';\nexport type {\n Pipeline,\n FieldRef,\n Accumulator,\n GroupResult,\n LookedUp,\n LookupTarget,\n} from './db/pipeline.js';\nexport { transaction } from './db/transaction.js';\nexport { ModelValidationError } from './db/schema.js';\nexport { scanDir } from './router/scan.js';\nexport { listTasks } from './tasks/index.js';\nexport { workerCount } from './cluster/index.js';\nexport type {\n EFCConfig,\n DatabasePoolConfig,\n CollectionSchema,\n CollectionFieldDefinition,\n GeoPoint,\n CorsConfig,\n RouteEntry,\n RouteMeta,\n RouteMethodMeta,\n RouteSchema,\n LoggingConfig,\n QueryLogConfig,\n CacheConfig,\n RequestSchema,\n Validator,\n ValidationIssue,\n TaskOptions,\n TaskDefinition,\n DatabaseEngine,\n AuthStrategy,\n ModelSchema,\n TableSchema,\n TableSchemaField,\n TableFieldDefinition,\n TableOptions,\n TableRelation,\n MigrationContext,\n SchemaField,\n Filter,\n FilterOperators,\n Update,\n FindOptions,\n IndexDefinition,\n ModelRecord,\n InferRecord,\n InferCreate,\n InferSchema,\n InferCreateInput,\n ScalarKeys,\n SortDirection,\n ModelCRUD,\n ModelQueryOptions,\n ModelOptions,\n FieldDefinition,\n DefaultOperator,\n} from './types.js';\n","import type { Request, RequestHandler } from 'express';\nimport type { RequestSchema, RouteSchema, ValidationIssue, Validator } from '../types.js';\n\nconst LOCATIONS = ['params', 'query', 'body'] as const;\ntype Location = (typeof LOCATIONS)[number];\n\ninterface StandardResult {\n value?: unknown;\n issues?: ReadonlyArray<{\n message: string;\n path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n }>;\n}\n\nfunction isRequestSchema(value: unknown): value is RequestSchema {\n return (\n value != null &&\n typeof value === 'object' &&\n LOCATIONS.some((loc) => loc in (value as Record<string, unknown>))\n );\n}\n\n/** Picks the schema for `method`: a method-keyed entry wins over a file-wide one. */\nexport function schemaFor(\n schema: RouteSchema | undefined,\n method: string,\n): RequestSchema | undefined {\n if (!schema) return undefined;\n const byMethod = (schema as Record<string, unknown>)[method];\n if (isRequestSchema(byMethod)) return byMethod;\n return isRequestSchema(schema) ? schema : undefined;\n}\n\ntype IssuePath = ReadonlyArray<PropertyKey | { key: PropertyKey }> | undefined;\n\nfunction pathToString(path: IssuePath): string {\n if (!path) return '';\n return path\n .map((p) => (typeof p === 'object' && p !== null && 'key' in p ? p.key : p))\n .map(String)\n .join('.');\n}\n\n// Standard Schema (zod >=3.24, valibot, arktype, ...) first; plain zod-style\n// safeParse as a fallback so older zod 3 releases work too.\nasync function run(validator: Validator, input: unknown): Promise<StandardResult> {\n const std = (validator as { '~standard'?: { validate: (v: unknown) => unknown } })['~standard'];\n if (std && typeof std.validate === 'function') {\n return (await std.validate(input)) as StandardResult;\n }\n const v = validator as {\n safeParseAsync?: (x: unknown) => Promise<unknown>;\n safeParse?: (x: unknown) => unknown;\n };\n const parse = v.safeParseAsync ?? v.safeParse;\n if (typeof parse !== 'function') {\n throw new Error('[EFC] Route schema entries must be Standard Schema validators (e.g. zod)');\n }\n const r = (await parse.call(validator, input)) as {\n success: boolean;\n data?: unknown;\n error?: { issues: Array<{ message: string; path: PropertyKey[] }> };\n };\n return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: 'Invalid' }] };\n}\n\n/**\n * Validates params/query/body against the route's schema. On success the parsed\n * output replaces the raw input (so coercions and defaults apply); on failure\n * responds 400 with every issue across all locations.\n */\nexport function validateRequest(schema: RequestSchema): RequestHandler {\n return (req, res, next) => {\n void (async () => {\n const issues: ValidationIssue[] = [];\n const parsed: Partial<Record<Location, unknown>> = {};\n\n for (const location of LOCATIONS) {\n const validator = schema[location];\n if (!validator) continue;\n const result = await run(validator, req[location]);\n if (result.issues) {\n for (const issue of result.issues) {\n issues.push({ location, path: pathToString(issue.path), message: issue.message });\n }\n } else {\n parsed[location] = result.value;\n }\n }\n\n if (issues.length > 0) {\n res.status(400).json({ error: 'Validation failed', statusCode: 400, issues });\n return;\n }\n\n for (const location of LOCATIONS) {\n if (location in parsed) {\n // req.query is a getter in some Express setups — define rather than assign.\n Object.defineProperty(req as Request, location, {\n value: parsed[location],\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n next();\n })().catch(next);\n };\n}\n","import type { IRouter, RequestHandler } from 'express';\nimport type { MountedRoute, RouteMeta, RouteEntry, RouteSchema } from '../types.js';\nimport { schemaFor, validateRequest } from './validate.js';\n\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const;\ntype HttpMethod = (typeof HTTP_METHODS)[number];\n\nfunction asyncWrap(handler: RequestHandler): RequestHandler {\n return (req, res, next) => {\n Promise.resolve(handler(req, res, next)).catch(next);\n };\n}\n\n/**\n * For RegExp-mounted (catch-all) routes, Express exposes captures as params[0..n].\n * Rename them to the segment names from the file path; catch-alls become string\n * arrays (`[...slug]` → `['a', 'b']`), absent optional segments become undefined.\n */\nfunction namedParams(route: RouteEntry): RequestHandler {\n const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\\*/g)].map((m) => m[1]!));\n return (req, _res, next) => {\n const positional = req.params as Record<string, string | undefined>;\n const named: Record<string, unknown> = {};\n route.params.forEach((name, i) => {\n const value = positional[String(i)];\n if (value === undefined || value === '') {\n named[name] = catchAlls.has(name) ? [] : undefined;\n } else if (catchAlls.has(name)) {\n named[name] = value.split('/').filter(Boolean).map(decodeURIComponent);\n } else {\n named[name] = decodeURIComponent(value);\n }\n });\n req.params = named as typeof req.params;\n next();\n };\n}\n\nexport async function mountRoutes(app: IRouter, routes: RouteEntry[]): Promise<MountedRoute[]> {\n const mounted: MountedRoute[] = [];\n\n for (const route of routes) {\n const mod = (await import(route.filePath)) as Record<string, unknown>;\n const routeMiddlewares: RequestHandler[] = Array.isArray(mod['middlewares'])\n ? (mod['middlewares'] as RequestHandler[])\n : [];\n\n const raw = mod['meta'];\n const meta: RouteMeta | undefined =\n raw != null && typeof raw === 'object' && !Array.isArray(raw)\n ? (raw as RouteMeta)\n : undefined;\n\n const schema =\n mod['schema'] != null && typeof mod['schema'] === 'object'\n ? (mod['schema'] as RouteSchema)\n : undefined;\n\n const routePath = route.pattern ?? route.urlPath;\n const paramMapper = route.pattern ? [namedParams(route)] : [];\n\n const implemented: HttpMethod[] = [];\n const unimplemented: HttpMethod[] = [];\n\n for (const method of HTTP_METHODS) {\n if (typeof mod[method] === 'function') {\n implemented.push(method);\n const methodSchema = schemaFor(schema, method);\n const validation = methodSchema ? [validateRequest(methodSchema)] : [];\n app[method.toLowerCase() as Lowercase<HttpMethod>](\n routePath,\n ...paramMapper,\n ...routeMiddlewares,\n ...validation,\n asyncWrap(mod[method] as RequestHandler),\n );\n } else {\n unimplemented.push(method);\n }\n }\n\n if (implemented.length > 0 && unimplemented.length > 0) {\n const allowHeader = implemented.join(', ');\n app.all(routePath, (req, res, next) => {\n if ((unimplemented as string[]).includes(req.method)) {\n res.set('Allow', allowHeader).status(405).json({ error: 'Method Not Allowed' });\n } else {\n next();\n }\n });\n }\n\n mounted.push({ ...route, methods: implemented, ...(meta !== undefined && { meta }) });\n }\n\n return mounted;\n}\n\nexport { asyncWrap };\n","import cluster from 'node:cluster';\nimport { getLogger } from '../logger.js';\n\ninterface ClusterOptions {\n workers?: number;\n onWorkerReady?: ((id: number) => void) | undefined;\n onWorkerCrash?: ((id: number, code: number) => void) | undefined;\n}\n\nlet isShuttingDown = false;\n\n/**\n * Returns the number of currently alive (not yet exited) cluster workers.\n * Returns `0` when running in single-process mode.\n */\nexport function workerCount(): number {\n return Object.keys(cluster.workers ?? {}).length;\n}\n\nexport function shutdownMaster(): void {\n isShuttingDown = true;\n getLogger().info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers…`);\n if (workerCount() === 0) process.exit(0);\n // Orchestrators (docker stop, k8s) signal only PID 1 — the primary — so forward the\n // signal; each worker's gracefulShutdown drains its server and exits on its own.\n for (const worker of Object.values(cluster.workers ?? {})) {\n worker?.process.kill('SIGTERM');\n }\n}\n\nexport function runMaster(options: ClusterOptions = {}): void {\n const count = options.workers ?? 1;\n\n getLogger().info(`Primary ${process.pid} starting ${count} workers`);\n\n for (let i = 0; i < count; i++) {\n cluster.fork();\n }\n\n cluster.on('online', (worker) => {\n options.onWorkerReady?.(worker.id);\n });\n\n cluster.on('exit', (worker, code, signal) => {\n const exitCode = code ?? (signal ? -1 : 0);\n if (isShuttingDown) {\n getLogger().info(`Worker ${worker.id} gracefully exited`);\n if (workerCount() === 0) {\n getLogger().info('All workers exited. Primary exiting.');\n process.exit(0);\n }\n return;\n }\n\n getLogger().warn(`Worker ${worker.id} exited (code=${exitCode}), respawning…`);\n options.onWorkerCrash?.(worker.id, exitCode);\n cluster.fork();\n });\n}\n\nexport { cluster };\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { registerTask } from './index.js';\nimport { getLogger } from '../logger.js';\nimport type { TaskDefinition } from '../types.js';\n\nexport async function scanTasks(tasksDir: string): Promise<void> {\n if (!fs.existsSync(tasksDir)) return;\n\n const files = fs.readdirSync(tasksDir).filter((f) => /\\.(ts|js|mts|mjs)$/.test(f));\n\n for (const file of files) {\n const filePath = path.join(tasksDir, file);\n const taskName = path.basename(file, path.extname(file));\n\n try {\n const mod = (await import(filePath)) as Record<string, unknown>;\n const def = mod['default'] as TaskDefinition | undefined;\n\n if (!def || typeof def.handler !== 'function') {\n getLogger().warn(`Task file ${file} has no valid default export — skipping`);\n continue;\n }\n\n registerTask(taskName, { ...def, filePath });\n getLogger().debug(`Registered task: ${taskName}`);\n } catch (err) {\n getLogger().warn({ err }, `Failed to load task ${file}`);\n }\n }\n}\n","import type { MountedRoute } from './types.js';\n\nconst HTTP_STATUS: Record<number, string> = {\n 200: 'OK',\n 201: 'Created',\n 202: 'Accepted',\n 204: 'No Content',\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 409: 'Conflict',\n 422: 'Unprocessable Entity',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n};\n\nexport function generateDashboard(\n routes: MountedRoute[],\n basePath: string,\n port: number,\n projectName: string,\n projectVersion: string,\n): string {\n const safeRoutes = JSON.stringify(\n routes.map((r) => ({\n urlPath: r.urlPath,\n methods: r.methods,\n params: r.params,\n meta: r.meta ?? null,\n })),\n ).replace(/<\\/script>/gi, '<\\\\/script>');\n const safeHttpStatus = JSON.stringify(HTTP_STATUS);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${projectName} — API Reference</title>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin />\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap\" rel=\"stylesheet\" />\n <style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n :root {\n --bg: #080b0f;\n --bg-card: #0d1117;\n --bg-raised: #111820;\n --border: #1e2832;\n --border-lit: #263040;\n --text: #e2e8f0;\n --text-dim: #64748b;\n --text-muted: #334155;\n --accent: #F0A030;\n --accent-dim: rgba(240,160,48,.12);\n --accent-glow: rgba(240,160,48,.22);\n --purple: #a78bfa;\n --blue: #60a5fa;\n --orange: #fb923c;\n --green: #7AAE8E;\n --radius: 10px;\n --radius-lg: 16px;\n --font-mono: 'JetBrains Mono', monospace;\n --font-sans: 'Inter', sans-serif;\n }\n html { scroll-behavior: smooth; }\n body {\n background: var(--bg); color: var(--text);\n font-family: var(--font-sans); font-size: 16px;\n line-height: 1.6; -webkit-font-smoothing: antialiased;\n position: relative;\n }\n body::before {\n content: ''; position: fixed; inset: 0; z-index: 0;\n background-image:\n linear-gradient(var(--border) 1px, transparent 1px),\n linear-gradient(90deg, var(--border) 1px, transparent 1px);\n background-size: 60px 60px; opacity: .28; pointer-events: none;\n }\n section, footer, .page-hero, .docs-layout { position: relative; z-index: 1; }\n a { text-decoration: none; color: inherit; }\n em { font-style: italic; }\n code {\n font-family: var(--font-mono); font-size: .85em;\n background: var(--bg-raised); border: 1px solid var(--border);\n border-radius: 4px; padding: 1px 6px; color: var(--accent);\n }\n .container { max-width: 1140px; margin: 0 auto; padding: 0 24px; }\n ::-webkit-scrollbar { width: 6px; }\n ::-webkit-scrollbar-track { background: var(--bg); }\n ::-webkit-scrollbar-thumb { background: var(--border-lit); border-radius: 3px; }\n\n /* ── PAGE HERO ── */\n .page-hero {\n padding: 48px 0 56px; border-bottom: 1px solid var(--border);\n }\n .page-hero .hero-glow {\n position: absolute; top: -40px; left: 10%; width: 500px; height: 350px;\n background: radial-gradient(ellipse, rgba(240,160,48,.1) 0%, transparent 68%);\n pointer-events: none;\n }\n .page-title {\n font-size: clamp(2rem, 5vw, 3.4rem); font-weight: 800;\n line-height: 1.1; letter-spacing: -.02em; margin-bottom: 24px;\n display: flex; align-items: baseline; gap: 16px; flex-wrap: wrap;\n }\n .project-version {\n font-family: var(--font-mono); font-size: clamp(.85rem, 2vw, 1.1rem);\n font-weight: 500; color: var(--accent);\n background: var(--accent-dim); border: 1px solid rgba(240,160,48,.3);\n border-radius: 6px; padding: 2px 10px; letter-spacing: .5px;\n }\n .hero-meta { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 40px; }\n .base-url-pill {\n display: flex; align-items: center; gap: 8px;\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: 7px; padding: 8px 14px;\n }\n .base-url-label { font-size: .72rem; font-family: var(--font-mono);\n color: var(--text-muted); text-transform: uppercase; letter-spacing: .5px; }\n .base-url-val { font-family: var(--font-mono); font-size: .8rem; color: var(--accent); }\n .count-pill {\n font-family: var(--font-mono); font-size: .72rem; color: var(--text-dim);\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: 7px; padding: 8px 14px;\n }\n\n /* ── TOOLBAR ── */\n .toolbar {\n display: flex; align-items: center; gap: 12px; flex-wrap: wrap;\n }\n .method-filters { display: flex; gap: 4px; flex-wrap: wrap; }\n .filter-btn {\n background: var(--bg-card); border: 1px solid var(--border);\n color: var(--text-dim); font-family: var(--font-mono);\n font-size: .72rem; font-weight: 600; letter-spacing: .5px;\n padding: 6px 12px; border-radius: 6px; cursor: pointer;\n transition: all .15s;\n }\n .filter-btn:hover { border-color: var(--border-lit); color: var(--text); }\n .filter-btn.active { background: var(--accent); color: #0d0d1a; border-color: var(--accent); }\n .filter-btn[data-method=\"GET\"].active { background: rgba(96,165,250,.18); color: #60a5fa; border-color: rgba(96,165,250,.4); }\n .filter-btn[data-method=\"POST\"].active { background: rgba(122,174,142,.18); color: #7AAE8E; border-color: rgba(122,174,142,.4); }\n .filter-btn[data-method=\"PUT\"].active { background: rgba(240,160,48,.18); color: #F0A030; border-color: rgba(240,160,48,.4); }\n .filter-btn[data-method=\"PATCH\"].active { background: rgba(251,191,36,.18); color: #fbbf24; border-color: rgba(251,191,36,.4); }\n .filter-btn[data-method=\"DELETE\"].active { background: rgba(248,113,113,.18); color: #f87171; border-color: rgba(248,113,113,.4); }\n .filter-btn[data-method=\"HEAD\"].active { background: rgba(167,139,250,.18); color: #a78bfa; border-color: rgba(167,139,250,.4); }\n .search-wrap { margin-left: auto; }\n .search-input {\n background: var(--bg-card); border: 1px solid var(--border);\n color: var(--text); font-family: var(--font-sans); font-size: .85rem;\n padding: 7px 14px; border-radius: 7px; width: 240px;\n outline: none; transition: border-color .2s;\n }\n .search-input::placeholder { color: var(--text-muted); }\n .search-input:focus { border-color: var(--border-lit); }\n\n /* ── DOCS LAYOUT ── */\n .docs-layout {\n display: grid; grid-template-columns: 260px 1fr;\n gap: 48px; padding: 52px 0 80px; max-width: 1140px;\n margin: 0 auto; padding-left: 24px; padding-right: 24px;\n align-items: start;\n }\n\n /* ── SIDEBAR ── */\n .docs-sidebar {\n position: sticky; top: 24px;\n max-height: calc(100vh - 48px);\n overflow-y: auto;\n overflow-x: hidden;\n scrollbar-width: none;\n padding-right: 4px;\n }\n .docs-sidebar::-webkit-scrollbar { display: none; }\n .sidebar-section { margin-bottom: 28px; }\n .sidebar-label {\n font-family: var(--font-mono); font-size: .68rem; font-weight: 600;\n color: var(--text-muted); letter-spacing: 1.2px; text-transform: uppercase;\n margin-bottom: 8px; padding: 0 4px;\n }\n .sidebar-link {\n display: flex; align-items: center; gap: 8px;\n padding: 7px 10px; border-radius: 6px;\n border-left: 2px solid transparent;\n font-size: .82rem; color: var(--text-dim); cursor: pointer;\n transition: background .15s, color .15s, border-color .15s;\n overflow: hidden; white-space: nowrap;\n }\n .sidebar-link:hover { background: var(--bg-raised); color: var(--text); }\n .sidebar-link.active { color: var(--accent); border-left-color: var(--accent); background: var(--accent-dim); }\n .sidebar-method-dot {\n width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0;\n }\n .sidebar-path { font-family: var(--font-mono); font-size: .72rem; }\n\n /* ── ENDPOINT CARDS ── */\n .endpoint-card {\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: var(--radius-lg); margin-bottom: 20px;\n overflow: hidden; transition: border-color .2s;\n animation: fadeUp .45s ease both;\n }\n .endpoint-card:hover { border-color: var(--border-lit); }\n @keyframes fadeUp {\n from { opacity: 0; transform: translateY(16px); }\n to { opacity: 1; transform: translateY(0); }\n }\n @media (prefers-reduced-motion: reduce) {\n .endpoint-card { animation: none; }\n }\n .endpoint-header {\n display: flex; align-items: center; gap: 14px;\n padding: 20px 24px 18px; border-bottom: 1px solid var(--border);\n flex-wrap: wrap;\n }\n .method-badges { display: flex; gap: 6px; flex-wrap: wrap; }\n .method-badge {\n font-family: var(--font-mono); font-size: .7rem; font-weight: 600;\n letter-spacing: .8px; padding: 4px 10px; border-radius: 5px;\n border: 1px solid; text-transform: uppercase;\n }\n .endpoint-path {\n font-family: var(--font-mono); font-size: .9rem; color: var(--text);\n background: none; border: none; padding: 0;\n word-break: break-all;\n }\n .endpoint-body { padding: 6px 24px 24px; }\n .endpoint-desc { font-size: .9rem; color: var(--text-dim); line-height: 1.7; margin-bottom: 20px; }\n\n /* ── PER-METHOD DOC BLOCKS ── */\n .method-block { padding-top: 20px; }\n .method-block + .method-block { margin-top: 4px; border-top: 1px solid var(--border); }\n .method-block-header { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }\n .method-block-header .method-badge { font-size: .68rem; }\n .method-block-empty { font-size: .82rem; color: var(--text-muted); }\n\n /* ── CODE BLOCKS ── */\n .example-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }\n .code-block-wrap {\n background: var(--bg-raised); border: 1px solid var(--border);\n border-radius: var(--radius); overflow: hidden;\n }\n .code-bar {\n display: flex; align-items: center; gap: 6px;\n padding: 9px 14px; border-bottom: 1px solid var(--border);\n background: var(--bg-card);\n }\n .dot { width: 11px; height: 11px; border-radius: 50%; }\n .dot-r { background: #ff5f57; }\n .dot-y { background: #febc2e; }\n .dot-g { background: #28c840; }\n .code-label { font-family: var(--font-mono); font-size: .68rem; color: var(--text-dim); margin-left: 4px; }\n pre.code-pre {\n font-family: var(--font-mono); font-size: .78rem; line-height: 1.7;\n padding: 16px 18px; overflow-x: auto; tab-size: 2; white-space: pre;\n }\n .c-dim { color: var(--text-muted); }\n .c-green { color: #7AAE8E; }\n .c-blue { color: #60a5fa; }\n .c-orange { color: #fb923c; }\n .c-purple { color: #a78bfa; }\n .c-accent { color: var(--accent); }\n .status-2xx { color: #7AAE8E; }\n .status-4xx { color: #f87171; }\n .status-5xx { color: #fb923c; }\n\n /* ── EMPTY STATE ── */\n .empty-state {\n text-align: center; padding: 80px 24px;\n color: var(--text-muted); font-size: .9rem;\n }\n\n /* ── RESPONSIVE ── */\n @media (max-width: 900px) {\n .docs-layout { grid-template-columns: 1fr; }\n .docs-sidebar { position: static; max-height: none; overflow-y: visible; padding-right: 0; }\n .example-grid { grid-template-columns: 1fr; }\n .search-wrap { margin-left: 0; width: 100%; }\n .search-input { width: 100%; }\n }\n @media (max-width: 600px) {\n .page-hero { padding: 32px 0 32px; }\n .page-title { font-size: 2rem; }\n }\n </style>\n</head>\n<body>\n\n <div class=\"page-hero\">\n <div class=\"hero-glow\"></div>\n <div class=\"container\">\n <h1 class=\"page-title\">${projectName}${projectVersion ? `<span class=\"project-version\">v${projectVersion}</span>` : ''}</h1>\n <div class=\"hero-meta\">\n <div class=\"base-url-pill\">\n <span class=\"base-url-label\">Base</span>\n <span class=\"base-url-val\">http://localhost:${port}${basePath}</span>\n </div>\n <div class=\"count-pill\" id=\"countPill\"></div>\n </div>\n <div class=\"toolbar\">\n <div class=\"method-filters\" id=\"methodFilters\">\n <button class=\"filter-btn active\" data-method=\"ALL\">ALL</button>\n </div>\n <div class=\"search-wrap\">\n <input type=\"text\" id=\"searchInput\" class=\"search-input\" placeholder=\"Search endpoints…\" />\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"docs-layout\">\n <aside class=\"docs-sidebar\" id=\"sidebar\"></aside>\n <main id=\"endpoints\"></main>\n </div>\n\n <script>\n const ROUTES = ${safeRoutes};\n const BASE_PATH = ${JSON.stringify(basePath)};\n const HTTP_STATUS = ${safeHttpStatus};\n\n const METHOD_STYLE = {\n GET: { bg: 'rgba(96,165,250,.14)', color: '#60a5fa', border: 'rgba(96,165,250,.35)' },\n POST: { bg: 'rgba(122,174,142,.14)', color: '#7AAE8E', border: 'rgba(122,174,142,.35)' },\n PUT: { bg: 'rgba(240,160,48,.14)', color: '#F0A030', border: 'rgba(240,160,48,.35)' },\n PATCH: { bg: 'rgba(251,191,36,.14)', color: '#fbbf24', border: 'rgba(251,191,36,.35)' },\n DELETE: { bg: 'rgba(248,113,113,.14)', color: '#f87171', border: 'rgba(248,113,113,.35)' },\n HEAD: { bg: 'rgba(167,139,250,.14)', color: '#a78bfa', border: 'rgba(167,139,250,.35)' },\n OPTIONS: { bg: 'rgba(148,163,184,.14)', color: '#94a3b8', border: 'rgba(148,163,184,.35)' },\n };\n\n function esc(s) {\n return String(s)\n .replace(/&/g,'&').replace(/</g,'<')\n .replace(/>/g,'>').replace(/\"/g,'"');\n }\n\n function methodBadge(m) {\n const s = METHOD_STYLE[m] || METHOD_STYLE.GET;\n return '<span class=\"method-badge\" style=\"background:' + s.bg + ';color:' + s.color + ';border-color:' + s.border + '\">' + m + '</span>';\n }\n\n function joinPath(base, p) {\n return (base.replace(/\\\\/+$/, '') + p) || '/';\n }\n\n function sidebarDot(method) {\n const s = METHOD_STYLE[method] || METHOD_STYLE.GET;\n return '<span class=\"sidebar-method-dot\" style=\"background:' + s.color + '\"></span>';\n }\n\n function statusClass(code) {\n if (code >= 200 && code < 300) return 'status-2xx';\n if (code >= 400 && code < 500) return 'status-4xx';\n if (code >= 500) return 'status-5xx';\n return '';\n }\n\n function renderSchema(val, indent) {\n const pad = ' '.repeat(indent || 0);\n if (val === null) return '<span class=\"c-dim\">null</span>';\n if (typeof val === 'string') {\n const isDate = /^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}/.test(val);\n return isDate ? '<span class=\"c-green\">Date</span>' : '<span class=\"c-purple\">String</span>';\n }\n if (typeof val === 'number') return '<span class=\"c-orange\">Number</span>';\n if (typeof val === 'boolean') return '<span class=\"c-purple\">Boolean</span>';\n if (Array.isArray(val)) {\n if (!val.length) return '[]';\n return '[\\\\n' + pad + ' ' + renderSchema(val[0], (indent || 0) + 1) + '\\\\n' + pad + ']';\n }\n if (typeof val === 'object') {\n const keys = Object.keys(val);\n if (!keys.length) return '{}';\n const inner = keys.map(function(k) {\n return pad + ' <span class=\"c-blue\">"' + esc(k) + '"</span>: ' + renderSchema(val[k], (indent || 0) + 1);\n }).join(',\\\\n');\n return '{\\\\n' + inner + '\\\\n' + pad + '}';\n }\n return esc(String(val));\n }\n\n function codeBlock(label, content) {\n return '<div class=\"code-block-wrap\">' +\n '<div class=\"code-bar\">' +\n '<span class=\"dot dot-r\"></span>' +\n '<span class=\"dot dot-y\"></span>' +\n '<span class=\"dot dot-g\"></span>' +\n '<span class=\"code-label\">' + esc(label) + '</span>' +\n '</div>' +\n '<pre class=\"code-pre\">' + content + '</pre>' +\n '</div>';\n }\n\n function buildRequestContent(route, method, example) {\n const req = example || {};\n let path = joinPath(BASE_PATH, route.urlPath);\n if (req.params) {\n for (const [k, v] of Object.entries(req.params)) {\n path = path.replace(':' + k, String(v));\n }\n }\n if (req.query && Object.keys(req.query).length) {\n path += '?' + new URLSearchParams(req.query).toString();\n }\n let lines = '<span class=\"c-accent\">' + esc(method) + '</span> <span class=\"c-blue\">' + esc(path) + '</span>';\n const headers = { ...(req.headers || {}) };\n if (req.body !== undefined && !headers['Content-Type']) {\n headers['Content-Type'] = 'application/json';\n }\n if (Object.keys(headers).length) {\n lines += '\\\\n' + Object.entries(headers)\n .map(([k, v]) => '<span class=\"c-dim\">' + esc(k) + ':</span> ' + esc(String(v)))\n .join('\\\\n');\n }\n if (req.body !== undefined) {\n lines += '\\\\n\\\\n' + renderSchema(req.body, 0);\n }\n return lines;\n }\n\n function buildResponseContent(example) {\n const resp = example || {};\n const code = resp.status || 200;\n const text = HTTP_STATUS[code] || 'OK';\n const cls = statusClass(code);\n let lines = 'HTTP/1.1 <span class=\"' + cls + '\">' + code + ' ' + esc(text) + '</span>';\n if (resp.body !== undefined) {\n lines += '\\\\n<span class=\"c-dim\">Content-Type:</span> application/json\\\\n\\\\n';\n lines += renderSchema(resp.body, 0);\n }\n return lines;\n }\n\n function renderMethodBlock(route, method) {\n const methodMeta = route.meta ? route.meta[method] : null;\n const header = '<div class=\"method-block-header\">' + methodBadge(method) + '</div>';\n\n if (!methodMeta) {\n return '<div class=\"method-block\" data-method=\"' + esc(method) + '\">' + header +\n '<p class=\"method-block-empty\">No documentation provided for this method.</p></div>';\n }\n\n const desc = methodMeta.description\n ? '<p class=\"endpoint-desc\">' + esc(methodMeta.description) + '</p>'\n : '';\n const reqHtml = methodMeta.request !== undefined\n ? codeBlock('request', buildRequestContent(route, method, methodMeta.request))\n : '';\n const respHtml = methodMeta.response !== undefined\n ? codeBlock('response', buildResponseContent(methodMeta.response))\n : '';\n const examples = reqHtml || respHtml\n ? '<div class=\"example-grid\">' + reqHtml + respHtml + '</div>'\n : '';\n\n return '<div class=\"method-block\" data-method=\"' + esc(method) + '\">' + header + desc + examples + '</div>';\n }\n\n function renderCard(route, index) {\n const id = 'ep-' + index;\n const fullPath = joinPath(BASE_PATH, route.urlPath);\n const badges = route.methods.map(methodBadge).join('');\n const body = route.methods.map(function(m) { return renderMethodBlock(route, m); }).join('');\n const delay = (index * 0.06).toFixed(2) + 's';\n return '<div class=\"endpoint-card\" id=\"' + id + '\" data-methods=\"' + route.methods.join(',') + '\" data-path=\"' + esc(fullPath) + '\" style=\"animation-delay:' + delay + '\">' +\n '<div class=\"endpoint-header\">' +\n '<div class=\"method-badges\">' + badges + '</div>' +\n '<code class=\"endpoint-path\">' + esc(fullPath) + '</code>' +\n '</div>' +\n '<div class=\"endpoint-body\">' + body + '</div>' +\n '</div>';\n }\n\n function buildMethodFilters() {\n const allMethods = [...new Set(ROUTES.flatMap(r => r.methods))].sort();\n const filtersEl = document.getElementById('methodFilters');\n allMethods.forEach(m => {\n const btn = document.createElement('button');\n btn.className = 'filter-btn';\n btn.dataset.method = m;\n btn.textContent = m;\n filtersEl.appendChild(btn);\n });\n }\n\n function buildSidebar(routes) {\n const sidebar = document.getElementById('sidebar');\n if (!routes.length) { sidebar.innerHTML = ''; return; }\n\n const label = document.createElement('div');\n label.className = 'sidebar-label';\n label.textContent = 'Endpoints';\n sidebar.appendChild(label);\n\n routes.forEach((route, i) => {\n const link = document.createElement('div');\n link.className = 'sidebar-link';\n link.dataset.target = 'ep-' + ROUTES.indexOf(route);\n link.innerHTML = sidebarDot(route.methods[0] || 'GET') +\n '<span class=\"sidebar-path\">' + esc(route.urlPath || '/') + '</span>';\n link.addEventListener('click', () => {\n const target = document.getElementById(link.dataset.target);\n if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });\n });\n sidebar.appendChild(link);\n });\n }\n\n let activeFilter = 'ALL';\n let searchQuery = '';\n\n function applyFilters() {\n const cards = document.querySelectorAll('.endpoint-card');\n let visible = 0;\n cards.forEach(card => {\n const methods = card.dataset.methods.split(',');\n const path = card.dataset.path || '';\n const matchMethod = activeFilter === 'ALL' || methods.includes(activeFilter);\n const matchSearch = !searchQuery || path.toLowerCase().includes(searchQuery);\n const show = matchMethod && matchSearch;\n card.style.display = show ? '' : 'none';\n if (show) visible++;\n });\n document.getElementById('empty-state').style.display = visible ? 'none' : 'block';\n\n // Sync sidebar visibility\n document.querySelectorAll('.sidebar-link').forEach(link => {\n const targetId = link.dataset.target;\n const targetCard = document.getElementById(targetId);\n link.style.display = targetCard && targetCard.style.display !== 'none' ? '' : 'none';\n });\n }\n\n function init() {\n const count = ROUTES.length;\n document.getElementById('countPill').textContent = count + ' endpoint' + (count !== 1 ? 's' : '');\n\n buildMethodFilters();\n\n const container = document.getElementById('endpoints');\n container.innerHTML = ROUTES.map((r, i) => renderCard(r, i)).join('');\n\n // Add empty state after cards\n const emptyEl = document.createElement('div');\n emptyEl.id = 'empty-state';\n emptyEl.className = 'empty-state';\n emptyEl.style.display = 'none';\n emptyEl.innerHTML = '<p>No endpoints match your filter.</p>';\n container.after(emptyEl);\n\n buildSidebar(ROUTES);\n\n // Method filter clicks\n document.getElementById('methodFilters').addEventListener('click', e => {\n const btn = e.target.closest('.filter-btn');\n if (!btn) return;\n document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));\n btn.classList.add('active');\n activeFilter = btn.dataset.method;\n applyFilters();\n });\n\n // Search\n document.getElementById('searchInput').addEventListener('input', e => {\n searchQuery = e.target.value.trim().toLowerCase();\n applyFilters();\n });\n\n // Scroll spy for sidebar\n const cardEls = document.querySelectorAll('.endpoint-card');\n const sidebarLinks = document.querySelectorAll('.sidebar-link');\n const observer = new IntersectionObserver(entries => {\n entries.forEach(entry => {\n if (entry.isIntersecting) {\n const id = entry.target.id;\n sidebarLinks.forEach(l => l.classList.toggle('active', l.dataset.target === id));\n const sidebar = document.getElementById('sidebar');\n const activeLink = sidebar && sidebar.querySelector('.sidebar-link.active');\n if (sidebar && activeLink) {\n const linkTop = activeLink.getBoundingClientRect().top - sidebar.getBoundingClientRect().top + sidebar.scrollTop;\n sidebar.scrollTo({ top: linkTop, behavior: 'smooth' });\n }\n }\n });\n }, { rootMargin: '-80px 0px -60% 0px' });\n cardEls.forEach(el => observer.observe(el));\n\n }\n\n try {\n init();\n } catch (e) {\n document.body.insertAdjacentHTML('afterbegin',\n '<div style=\"position:fixed;top:60px;left:0;right:0;z-index:9999;background:#7f1d1d;color:#fca5a5;padding:16px 24px;font-family:monospace;font-size:13px;border-bottom:1px solid #ef4444\">' +\n '<strong>Dashboard JS error:</strong> ' + (e && e.message ? e.message : String(e)) +\n (e && e.stack ? '<pre style=\"margin-top:8px;white-space:pre-wrap\">' + e.stack + '</pre>' : '') +\n '</div>'\n );\n }\n </script>\n</body>\n</html>`;\n}\n","import type { Request, RequestHandler } from 'express';\nimport { isCacheConfigured, rawIncr } from './cache/index.js';\nimport { getLogger } from './logger.js';\n\n// rateLimit(): a fixed-window limit (windows aligned to the clock) counted in the cache\n// (`cache.incr`), so every worker — and with Redis every instance — shares one count. An\n// in-memory counter per worker would let N workers accept N × max.\n\nexport interface RateLimitOptions {\n /** Window length: seconds, or `'30s'`, `'15m'`, `'1h'`, `'1d'`. */\n window: number | string;\n /** Requests allowed per window and key. */\n max: number;\n /**\n * Who a request counts against. Default: the client IP (`req.ip`) — behind a proxy or load\n * balancer set `trustProxy` in ignite(), or every client shares the proxy's IP. Return\n * `undefined` to not limit this request.\n */\n key?: (req: Request) => string | undefined;\n /**\n * Which counter: requests to routes with the same name share a limit. Default: the route\n * pattern (`/users/:id`), so each route file has its own — or the path, for middleware\n * that isn't on a route.\n */\n name?: string;\n /** Body of the 429 response. Default: `'Too many requests, try again later'`. */\n message?: string;\n /**\n * The cache can't be reached: `'allow'` (default) lets requests through — a limiter\n * shouldn't take the API down with it; `'reject'` answers 503.\n */\n onCacheError?: 'allow' | 'reject';\n /** Send `RateLimit-Limit/Remaining/Reset` (and `Retry-After` on 429). Default: true. */\n headers?: boolean;\n}\n\nconst UNITS: Record<string, number> = { s: 1, m: 60, h: 3600, d: 86_400 };\n\nexport function parseWindow(window: number | string): number {\n if (typeof window === 'number') {\n if (window > 0) return window;\n } else {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*(s|m|h|d)$/.exec(window.trim());\n if (m) return Number(m[1]) * UNITS[m[2]!]!;\n }\n throw new Error(`[EFC] rateLimit: window must be seconds or like '15m' — got ${String(window)}`);\n}\n\nlet lastCacheError = 0;\n\n/**\n * Limits requests per key (default: client IP) to `max` per `window`, counted in the cache\n * so the limit holds across every worker and instance:\n *\n * ```ts\n * export const middlewares = [rateLimit({ window: '15m', max: 10 })];\n * ```\n *\n * Needs `cache` in ignite() — use the Redis backend when you run more than one instance.\n */\nexport function rateLimit(options: RateLimitOptions): RequestHandler {\n const windowSeconds = parseWindow(options.window);\n if (!Number.isInteger(options.max) || options.max < 1) {\n throw new Error('[EFC] rateLimit: max must be a positive integer');\n }\n const keyOf = options.key ?? ((req: Request) => req.ip ?? req.socket.remoteAddress);\n const message = options.message ?? 'Too many requests, try again later';\n const headers = options.headers ?? true;\n\n return (req, res, next) => {\n void (async () => {\n const who = keyOf(req);\n if (who === undefined) return next();\n if (!isCacheConfigured()) {\n throw new Error('[EFC] rateLimit needs a cache — pass cache: { backend } to ignite()');\n }\n const bucket = options.name ?? req.baseUrl + (req.route?.path ?? req.path);\n // Windows are aligned to the clock: every key restarts at the same boundary, and the\n // reset is exact. The key outlives its window by a second, then expires.\n const windowMs = windowSeconds * 1000;\n const now = Date.now();\n const slot = Math.floor(now / windowMs);\n const resetMs = (slot + 1) * windowMs - now;\n let count: number;\n try {\n count = (await rawIncr(`rl:${bucket}:${who}:${slot}`, Math.ceil(resetMs / 1000) + 1)).value;\n } catch (err) {\n if (Date.now() - lastCacheError > 30_000) {\n lastCacheError = Date.now();\n getLogger().error(\n { err },\n `rateLimit: cache unavailable — ${options.onCacheError === 'reject' ? 'rejecting with 503' : 'allowing requests'}`,\n );\n }\n if (options.onCacheError === 'reject') {\n res.status(503).json({ error: 'Service Unavailable', statusCode: 503 });\n return;\n }\n return next();\n }\n const resetSeconds = Math.max(1, Math.ceil(resetMs / 1000));\n if (headers) {\n res.setHeader('RateLimit-Limit', String(options.max));\n res.setHeader('RateLimit-Remaining', String(Math.max(0, options.max - count)));\n res.setHeader('RateLimit-Reset', String(resetSeconds));\n }\n if (count > options.max) {\n if (headers) res.setHeader('Retry-After', String(resetSeconds));\n res.status(429).json({ error: message, statusCode: 429 });\n return;\n }\n next();\n })().catch(next);\n };\n}\n","import type { Request, RequestHandler } from 'express';\nimport { cache } from './index.js';\nimport { getCurrentUser } from '../context.js';\n\nexport interface CacheResponseOptions {\n /** Seconds to keep a response. */\n ttl: number;\n /**\n * Cache per authenticated user (keyed by the JWT's `sub`/`id`). Put `requireAuth`\n * before this middleware. Without it, a response is shared by everyone hitting the URL.\n */\n perUser?: boolean;\n /** Custom cache key. Default: the request's original URL (path + query). */\n key?: (req: Request) => string;\n}\n\ninterface Stored {\n status: number;\n body: unknown;\n}\n\n/** Key prefix for cached responses — `cache.clear(RESPONSE_PREFIX + '/v1/api/posts')` drops those. */\nexport const RESPONSE_PREFIX = 'res:';\n\n/**\n * Caches successful (200) JSON responses of GET/HEAD requests. Adds `X-Cache: HIT|MISS`.\n *\n * @example\n * export const middlewares = [cacheResponse(60)];\n * export const middlewares = [requireAuth, cacheResponse({ ttl: 30, perUser: true })];\n */\nexport function cacheResponse(options: number | CacheResponseOptions): RequestHandler {\n const opts: CacheResponseOptions = typeof options === 'number' ? { ttl: options } : options;\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') return next();\n\n let scope = '';\n if (opts.perUser) {\n const user = getCurrentUser();\n const id = user?.['sub'] ?? user?.['id'];\n // Never fall back to a shared entry for a per-user route.\n if (id === undefined) return next();\n scope = `u:${String(id)}:`;\n }\n const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);\n\n void (async () => {\n const hit = await cache.get<Stored>(key);\n if (hit) {\n res.setHeader('X-Cache', 'HIT');\n res.status(hit.status).json(hit.body);\n return;\n }\n res.setHeader('X-Cache', 'MISS');\n const json = res.json.bind(res);\n res.json = (body: unknown) => {\n if (res.statusCode === 200) void cache.set(key, { status: 200, body }, { ttl: opts.ttl });\n return json(body);\n };\n next();\n })().catch(next);\n };\n}\n","import type { RequestHandler } from 'express';\n\n/**\n * Chains multiple Express request handlers into a single handler.\n * Each handler calls the next one via its `next` callback.\n *\n * @example\n * export const GET = compose(requireAuth, rateLimiter, myHandler);\n */\nexport function compose(...handlers: RequestHandler[]): RequestHandler {\n return (req, res, next) => {\n function dispatch(i: number): void {\n if (i >= handlers.length) {\n next();\n return;\n }\n const handler = handlers[i];\n if (!handler) {\n next();\n return;\n }\n try {\n Promise.resolve(handler(req, res, () => dispatch(i + 1))).catch(next);\n } catch (err) {\n next(err);\n }\n }\n\n dispatch(0);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAOA,SAAQ;AACf,OAAO,aAAa;AACpB,OAAO,UAAU;AACjB,OAAO,kBAAkB;AACzB,OAAOC,cAAa;AACpB,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D,iBAAW,MAAM;AACf,kBAAU,EAAE,MAAM,2BAA2B;AAC7C,gBAAQ,KAAK,CAAC;AAAA,MAChB,GAAG,SAAS,EAAE,MAAM;AAAA,IACtB,OAAO;AACL,qBAAe;AAEf,iBAAW,MAAM;AACf,kBAAU,EAAE,MAAM,0DAAqD;AACvE,gBAAQ,KAAK,CAAC;AAAA,MAChB,GAAG,YAAY,GAAK,EAAE,MAAM;AAAA,IAC9B;AAAA,EACF;AACA,UAAQ,GAAG,WAAW,MAAM,SAAS,SAAS,CAAC;AAC/C,UAAQ,GAAG,UAAU,MAAM,SAAS,QAAQ,CAAC;AAC/C;","names":["fs","cluster","path","path","path","fs","cluster"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
closePgBoss,
|
|
3
|
+
initPgBoss,
|
|
4
|
+
pgBossAdmin
|
|
5
|
+
} from "./chunk-R4XO4SVM.js";
|
|
6
|
+
import "./chunk-R52CUEGT.js";
|
|
7
|
+
import "./chunk-RAB44UGX.js";
|
|
8
|
+
import "./chunk-73XJUT2S.js";
|
|
9
|
+
export {
|
|
10
|
+
closePgBoss,
|
|
11
|
+
initPgBoss,
|
|
12
|
+
pgBossAdmin
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=pgboss-backend-FW42SBSM.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
var _chunk7KO4DJRJcjs = require('./chunk-7KO4DJRJ.cjs');
|
|
6
|
+
require('./chunk-WBLUGOAG.cjs');
|
|
7
|
+
require('./chunk-GBI77W5T.cjs');
|
|
8
|
+
require('./chunk-DUADUR6R.cjs');
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
exports.closePgBoss = _chunk7KO4DJRJcjs.closePgBoss; exports.initPgBoss = _chunk7KO4DJRJcjs.initPgBoss; exports.pgBossAdmin = _chunk7KO4DJRJcjs.pgBossAdmin;
|
|
14
|
+
//# sourceMappingURL=pgboss-backend-RVHUBJTU.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/pgboss-backend-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/pgboss-backend-RVHUBJTU.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACA;AACF,4JAAC","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/pgboss-backend-RVHUBJTU.cjs"}
|
package/dist/registry/index.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "0.
|
|
2
|
+
"version": "0.10.0",
|
|
3
3
|
"variants": [
|
|
4
4
|
{
|
|
5
5
|
"key": "ts-mongo",
|
|
@@ -7,6 +7,12 @@
|
|
|
7
7
|
"database": "mongodb",
|
|
8
8
|
"modelApi": "defineModel"
|
|
9
9
|
},
|
|
10
|
+
{
|
|
11
|
+
"key": "ts-mongo-collection",
|
|
12
|
+
"language": "typescript",
|
|
13
|
+
"database": "mongodb",
|
|
14
|
+
"modelApi": "defineCollection"
|
|
15
|
+
},
|
|
10
16
|
{
|
|
11
17
|
"key": "ts-pg-model",
|
|
12
18
|
"language": "typescript",
|
|
@@ -25,6 +31,12 @@
|
|
|
25
31
|
"database": "mongodb",
|
|
26
32
|
"modelApi": "defineModel"
|
|
27
33
|
},
|
|
34
|
+
{
|
|
35
|
+
"key": "js-mongo-collection",
|
|
36
|
+
"language": "javascript",
|
|
37
|
+
"database": "mongodb",
|
|
38
|
+
"modelApi": "defineCollection"
|
|
39
|
+
},
|
|
28
40
|
{
|
|
29
41
|
"key": "js-pg-model",
|
|
30
42
|
"language": "javascript",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, id) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n return refreshToken;\n}\n\nexport const POST = async (req, res) => {\n const { email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || typeof password !== 'string' || !email || !password) {\n return res.status(400).json({ error: 'email and password are required' });\n }\n\n const admin = await Admin.findOne({ email });\n if (admin) {\n const match = await verifyPassword(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n const token = await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n const refreshToken = await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin', ...(token ? { token, refreshToken } : {}) });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await verifyPassword(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n const token = await issueToken(res, { id: user.id, role: user.role, email: user.email });\n const refreshToken = await issueRefreshToken(res, User, user.id);\n // bearer: the client stores both tokens itself; http-only: they travel as cookies.\n res.json({ message: 'Logged in', ...(token ? { token, refreshToken } : {}) });\n};\n"},{"path":"src/api/auth/logout.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof name !== 'string' || typeof email !== 'string' || typeof password !== 'string' || !name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
1
|
+
{"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport { rateLimit } from 'express-file-cluster';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\n// 10 attempts per 15 minutes per address and account. Keyed on the email too, so behind a\n// proxy without TRUST_PROXY (every client then has the proxy's IP) it still limits one\n// account at a time, never everyone.\nexport const middlewares = [\n rateLimit({\n window: '15m',\n max: 10,\n key: (req) => `${req.ip}:${String(req.body?.email ?? '').toLowerCase()}`,\n }),\n];\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, id) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n return refreshToken;\n}\n\nexport const POST = async (req, res) => {\n const { email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || typeof password !== 'string' || !email || !password) {\n return res.status(400).json({ error: 'email and password are required' });\n }\n\n const admin = await Admin.findOne({ email });\n if (admin) {\n const match = await verifyPassword(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n const token = await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n const refreshToken = await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin', ...(token ? { token, refreshToken } : {}) });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await verifyPassword(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n const token = await issueToken(res, { id: user.id, role: user.role, email: user.email });\n const refreshToken = await issueRefreshToken(res, User, user.id);\n // bearer: the client stores both tokens itself; http-only: they travel as cookies.\n res.json({ message: 'Logged in', ...(token ? { token, refreshToken } : {}) });\n};\n"},{"path":"src/api/auth/logout.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof name !== 'string' || typeof email !== 'string' || typeof password !== 'string' || !name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.js","content":"import crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req, res) => {\n const { email } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || !email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findOne({ email });\n const admin = user ? null : await Admin.findOne({ email });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update(user.id, { resetToken, resetTokenExpiry });\n else if (admin) await Admin.update(admin.id, { resetToken, resetTokenExpiry });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.js","content":"import { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { token, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof token !== 'string' || typeof password !== 'string' || !token || !password) {\n return res.status(400).json({ error: 'token and password are required' });\n }\n\n const user = await User.findOne({ resetToken: token });\n const admin = user ? null : await Admin.findOne({ resetToken: token });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n if (user) await User.update(user.id, { password: hashed, resetToken: '' });\n else if (admin) await Admin.update(admin.id, { password: hashed, resetToken: '' });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
1
|
+
{"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.js","content":"import crypto from 'node:crypto';\nimport { rateLimit } from 'express-file-cluster';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\n// 5 reset emails per hour per address — keeps the endpoint from mail-bombing someone.\nexport const middlewares = [\n rateLimit({ window: '1h', max: 5, key: (req) => String(req.body?.email ?? '').toLowerCase() }),\n];\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req, res) => {\n const { email } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || !email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findOne({ email });\n const admin = user ? null : await Admin.findOne({ email });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update(user.id, { resetToken, resetTokenExpiry });\n else if (admin) await Admin.update(admin.id, { resetToken, resetTokenExpiry });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.js","content":"import { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { token, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof token !== 'string' || typeof password !== 'string' || !token || !password) {\n return res.status(400).json({ error: 'token and password are required' });\n }\n\n const user = await User.findOne({ resetToken: token });\n const admin = user ? null : await Admin.findOne({ resetToken: token });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n if (user) await User.update(user.id, { password: hashed, resetToken: '' });\n else if (admin) await Admin.update(admin.id, { password: hashed, resetToken: '' });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"files":[{"path":"src/api/health.js","content":"export const meta = {\n GET: {\n description: 'Health check — returns server status and current timestamp.',\n response: { status: 200, body: { status: 'OK', timestamp: '2024-01-01T00:00:00.000Z' } },\n },\n};\n\nexport const GET = async (_req, res) => {\n res.json({ status: 'OK', timestamp: new Date().toISOString() });\n};\n"},{"path":"src/tasks/SendEmail.js","content":"import { defineTask } from 'express-file-cluster/tasks';\n\nexport default defineTask(async (payload) => {\n // TODO: wire up your mailer\n console.log('[SendEmail] Sending to', payload.to);\n});\n"}]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"account-security","files":[{"path":"src/api/auth/2fa/disable.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Disable 2FA for the authenticated user.',\n request: { body: { code: '123456' } },\n response: { status: 200, body: { message: '2FA disabled' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const POST = async (req, res) => {\n const { code } = req.body;\n if (!code) return res.status(400).json({ error: 'code is required' });\n // TODO: verify code and disable 2FA\n res.json({ message: '2FA disabled' });\n};\n"},{"path":"src/api/auth/2fa/setup.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Generate a TOTP secret and QR code to set up 2FA.',\n response: { status: 200, body: { qrCode: 'otpauth://totp/...', secret: 'BASE32SECRET' } },\n },\n POST: {\n description: 'Confirm a TOTP code to enable 2FA for the authenticated user.',\n request: { body: { code: '123456' } },\n response: { status: 200, body: { message: '2FA enabled' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n // TODO: generate TOTP secret and return QR code URL\n res.json({ qrCode: 'otpauth://totp/...', secret: 'BASE32SECRET' });\n};\n\nexport const POST = async (req, res) => {\n const { code } = req.body;\n if (!code) return res.status(400).json({ error: 'code is required' });\n // TODO: verify TOTP code and enable 2FA\n res.json({ message: '2FA enabled' });\n};\n"},{"path":"src/api/auth/2fa/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Verify a TOTP code during login.',\n request: { body: { code: '123456' } },\n response: { status: 200, body: { message: '2FA verified' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { code } = req.body;\n if (!code) return res.status(400).json({ error: 'code is required' });\n // TODO: verify TOTP code\n res.json({ message: '2FA verified' });\n};\n"},{"path":"src/api/auth/change-password.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Change password for the authenticated user.',\n request: { body: { oldPassword: 'current', newPassword: 'newpassword' } },\n response: { status: 200, body: { message: 'Password changed successfully' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const POST = async (req, res) => {\n const { oldPassword, newPassword } = req.body;\n if (!oldPassword || !newPassword) return res.status(400).json({ error: 'oldPassword and newPassword are required' });\n // TODO: verify old password, hash and update new password, then sign out other devices:\n // await revokeAllSessions(req.user.id) (import from 'express-file-cluster/auth')\n res.json({ message: 'Password changed successfully' });\n};\n"},{"path":"src/api/auth/refresh.js","content":"import { issueToken } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Refresh the JWT using the refresh-token cookie and issue a new access token.',\n response: { status: 200, body: { message: 'Token refreshed' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nexport const POST = async (req, res) => {\n const token = req.cookies?.efc_refresh_token || req.body?.refreshToken;\n if (!token) return res.status(401).json({ error: 'Refresh token required' });\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof token !== 'string') return res.status(400).json({ error: 'Invalid refresh token' });\n\n const user = await User.findOne({ refreshToken: token });\n const admin = user ? null : await Admin.findOne({ refreshToken: token });\n const account = user || admin;\n\n if (!account || !account.refreshTokenExpiry || new Date(account.refreshTokenExpiry) < new Date()) {\n return res.status(401).json({ error: 'Invalid or expired refresh token' });\n }\n if (account.isActive === false) return res.status(403).json({ error: 'Account suspended' });\n\n const newRefreshToken = crypto.randomBytes(40).toString('hex');\n const refreshTokenExpiry = new Date(Date.now() + REFRESH_TOKEN_TTL_MS);\n if (user) await User.findByIdAndUpdate(user.id, { refreshToken: newRefreshToken, refreshTokenExpiry }, { returnDocument: 'after' });\n else if (admin) await Admin.findByIdAndUpdate(admin.id, { refreshToken: newRefreshToken, refreshTokenExpiry }, { returnDocument: 'after' });\n\n res.cookie('efc_refresh_token', newRefreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n\n const accessToken = await issueToken(res, { id: account.id, role: account.role, email: account.email });\n // bearer: the client stores both tokens itself; http-only: they travel as cookies.\n res.json({\n message: 'Token refreshed',\n ...(accessToken ? { token: accessToken, refreshToken: newRefreshToken } : {}),\n });\n};\n"},{"path":"src/api/auth/sessions/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n DELETE: {\n description: 'Revoke a single active session by ID.',\n request: { params: { id: 'sess_01HXZ' } },\n response: { status: 200, body: { message: 'Session sess_01HXZ revoked' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n // TODO: revoke session by id\n res.json({ message: `Session ${id} revoked` });\n};\n"},{"path":"src/api/auth/sessions/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'List all active sessions for the authenticated user.',\n response: { status: 200, body: { sessions: [] } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n // TODO: fetch sessions for req.user.id\n res.json({ sessions: [] });\n};\n"},{"path":"src/model/Session.js","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Session = defineCollection('Session', {\n userId: { type: 'string', required: true },\n token: { type: 'string', required: true, unique: true },\n ip: { type: 'string', required: true },\n userAgent: { type: 'string', required: true },\n expiresAt: { type: 'date', required: true },\n isActive: { type: 'boolean', default: true },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"account-settings","files":[{"path":"src/api/user/account.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Download a personal data export for the authenticated user.',\n response: { status: 200, body: { data: { user: { id: '1', role: 'user', email: 'user@example.com' }, exportedAt: '2026-01-01T00:00:00.000Z' } } },\n },\n DELETE: {\n description: 'Schedule the authenticated account for deletion (requires password confirmation).',\n request: { body: { password: 'current' } },\n response: { status: 200, body: { message: 'Account scheduled for deletion' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n // TODO: compile and return personal data export\n res.json({ data: { user: req.user, exportedAt: new Date().toISOString() } });\n};\n\nexport const DELETE = async (req, res) => {\n const { password } = req.body;\n if (!password) return res.status(400).json({ error: 'password confirmation required' });\n // TODO: verify password, schedule account deletion\n res.json({ message: 'Account scheduled for deletion' });\n};\n"},{"path":"src/api/user/activity.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Paginated activity history for the authenticated user.',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { activities: [], total: 0, page: 1, limit: 20 } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n const { page = 1, limit = 20 } = req.query;\n // TODO: fetch paginated activity log\n res.json({ activities: [], total: 0, page: Number(page), limit: Number(limit) });\n};\n"},{"path":"src/api/user/avatar.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Upload a new avatar image for the authenticated user.',\n response: { status: 200, body: { message: 'Avatar updated', url: 'https://example.com/avatar.jpg' } },\n },\n DELETE: {\n description: 'Remove the authenticated user\\'s avatar.',\n response: { status: 200, body: { message: 'Avatar removed' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const POST = async (req, res) => {\n // TODO: handle multipart upload, store file, update user.avatar\n res.json({ message: 'Avatar updated', url: 'https://example.com/avatar.jpg' });\n};\n\nexport const DELETE = async (req, res) => {\n // TODO: remove avatar and clear user.avatar\n res.json({ message: 'Avatar removed' });\n};\n"},{"path":"src/api/user/dashboard.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Personal dashboard: stats, recent activity, and quick actions.',\n response: { status: 200, body: { stats: {}, recentActivity: [], quickActions: [] } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n // TODO: aggregate personal stats and activity\n res.json({ stats: {}, recentActivity: [], quickActions: [] });\n};\n"},{"path":"src/api/user/settings.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Get account settings (notifications, language, theme, privacy) for the authenticated user.',\n response: { status: 200, body: { settings: { notifications: true, language: 'en', theme: 'system', privacy: 'public' } } },\n },\n PUT: {\n description: 'Update account settings for the authenticated user.',\n request: { body: { notifications: true, language: 'en', theme: 'system', privacy: 'public' } },\n response: { status: 200, body: { message: 'Settings updated', settings: { notifications: true, language: 'en', theme: 'system', privacy: 'public' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n // TODO: fetch user settings from DB\n res.json({ settings: { notifications: true, language: 'en', theme: 'system', privacy: 'public' } });\n};\n\nexport const PUT = async (req, res) => {\n const { notifications, language, theme, privacy } = req.body;\n // TODO: update user settings in DB\n res.json({ message: 'Settings updated', settings: { notifications, language, theme, privacy } });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-admins","files":[{"path":"src/api/admin/admins/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Fetch a single admin account by ID (admin only).',\n request: { params: { id: 'adm_01HXZ' } },\n response: { status: 200, body: { admin: { id: 'adm_01HXZ' } } },\n },\n PUT: {\n description: 'Update an admin account by ID (admin only).',\n request: { params: { id: 'adm_01HXZ' }, body: { name: 'Jane Doe', role: 'admin' } },\n response: { status: 200, body: { message: 'Admin updated', admin: { id: 'adm_01HXZ', name: 'Jane Doe', role: 'admin' } } },\n },\n DELETE: {\n description: 'Delete an admin account by ID (admin only).',\n request: { params: { id: 'adm_01HXZ' } },\n response: { status: 200, body: { message: 'Admin adm_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n // TODO: fetch admin by id\n res.json({ admin: { id } });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n // TODO: update admin record\n res.json({ message: 'Admin updated', admin: { id, ...req.body } });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n // TODO: delete admin\n res.json({ message: `Admin ${id} deleted` });\n};\n"},{"path":"src/api/admin/admins/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'List all admin accounts (admin only).',\n response: { status: 200, body: { admins: [], total: 0 } },\n },\n POST: {\n description: 'Create a new admin account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', role: 'admin' } },\n response: { status: 201, body: { message: 'Admin created', admin: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'admin' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: fetch admins from DB\n res.json({ admins: [], total: 0 });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, role } = req.body;\n if (!name || !email) return res.status(400).json({ error: 'name and email are required' });\n // TODO: create admin account\n res.status(201).json({ message: 'Admin created', admin: { id: 'new-id', name, email, role: role ?? 'admin' } });\n};\n"},{"path":"src/api/admin/roles/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Fetch a single role by ID (admin only).',\n request: { params: { id: 'role_01HXZ' } },\n response: { status: 200, body: { role: { id: 'role_01HXZ', name: 'editor', permissions: ['content:write'] } } },\n },\n PUT: {\n description: 'Update a role by ID (admin only).',\n request: { params: { id: 'role_01HXZ' }, body: { name: 'editor', permissions: ['content:write'] } },\n response: { status: 200, body: { message: 'Role updated', role: { id: 'role_01HXZ', name: 'editor', permissions: ['content:write'] } } },\n },\n DELETE: {\n description: 'Delete a role by ID (admin only).',\n request: { params: { id: 'role_01HXZ' } },\n response: { status: 200, body: { message: 'Role role_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n // TODO: fetch role by id\n res.json({ role: { id } });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n // TODO: update role\n res.json({ message: 'Role updated', role: { id, ...req.body } });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n // TODO: delete role\n res.json({ message: `Role ${id} deleted` });\n};\n"},{"path":"src/api/admin/roles/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'List all roles (admin only).',\n response: { status: 200, body: { roles: [] } },\n },\n POST: {\n description: 'Create a new role (admin only).',\n request: { body: { name: 'editor', description: 'Can edit content', permissions: ['content:write'] } },\n response: { status: 201, body: { message: 'Role created', role: { id: 'new-id', name: 'editor', permissions: ['content:write'] } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: fetch all roles\n res.json({ roles: [] });\n};\n\nexport const POST = async (req, res) => {\n const { name, description, permissions } = req.body;\n if (!name) return res.status(400).json({ error: 'name is required' });\n // TODO: create role\n res.status(201).json({ message: 'Role created', role: { id: 'new-id', name, permissions: permissions ?? [] } });\n};\n"},{"path":"src/model/Role.js","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Role = defineCollection('Role', {\n name: { type: 'string', required: true, unique: true },\n description: { type: 'string', required: true },\n permissions: { type: 'array', of: 'string', default: [] },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-analytics","files":[{"path":"src/api/admin/analytics/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Analytics overview: users, revenue, traffic (admin only).',\n response: { status: 200, body: { users: {}, revenue: {}, traffic: {} } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n // TODO: aggregate analytics overview\n res.json({ users: {}, revenue: {}, traffic: {} });\n};\n"},{"path":"src/api/admin/analytics/revenue.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Revenue analytics: MRR, ARR, payment history (admin only).',\n request: { query: { period: '30d' } },\n response: { status: 200, body: { mrr: 0, arr: 0, history: [], period: '30d' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { period = '30d' } = req.query;\n // TODO: fetch revenue analytics for period\n res.json({ mrr: 0, arr: 0, history: [], period });\n};\n"},{"path":"src/api/admin/analytics/traffic.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Traffic analytics: page views, devices, countries (admin only).',\n request: { query: { period: '30d' } },\n response: { status: 200, body: { pageViews: 0, devices: {}, countries: {}, period: '30d' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { period = '30d' } = req.query;\n // TODO: fetch traffic analytics for period\n res.json({ pageViews: 0, devices: {}, countries: {}, period });\n};\n"},{"path":"src/api/admin/analytics/users.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'User analytics: registrations, active users, churn (admin only).',\n request: { query: { period: '30d' } },\n response: { status: 200, body: { registrations: [], activeUsers: 0, churn: 0, period: '30d' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { period = '30d' } = req.query;\n // TODO: fetch user analytics for period\n res.json({ registrations: [], activeUsers: 0, churn: 0, period });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|