express-file-cluster 0.3.15 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -33
- package/dist/auth/index.cjs +12 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +13 -2
- package/dist/auth/index.d.ts +13 -2
- package/dist/auth/index.js +12 -2
- package/dist/chunk-3VWD2ZED.js +60 -0
- package/dist/chunk-3VWD2ZED.js.map +1 -0
- package/dist/chunk-47K2532L.cjs +196 -0
- package/dist/chunk-47K2532L.cjs.map +1 -0
- package/dist/chunk-5PDAWMGF.js +438 -0
- package/dist/chunk-5PDAWMGF.js.map +1 -0
- package/dist/chunk-7YEX4MQV.cjs +38 -0
- package/dist/chunk-7YEX4MQV.cjs.map +1 -0
- package/dist/chunk-ALBDM5R3.cjs +60 -0
- package/dist/chunk-ALBDM5R3.cjs.map +1 -0
- package/dist/chunk-JJJJTACK.js +196 -0
- package/dist/chunk-JJJJTACK.js.map +1 -0
- package/dist/chunk-LJNSJFOL.js +38 -0
- package/dist/chunk-LJNSJFOL.js.map +1 -0
- package/dist/chunk-M7MUPWCE.js +116 -0
- package/dist/chunk-M7MUPWCE.js.map +1 -0
- package/dist/chunk-PMF4GMHD.js +154 -0
- package/dist/chunk-PMF4GMHD.js.map +1 -0
- package/dist/chunk-QTRGJ2EN.cjs +2635 -0
- package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
- package/dist/chunk-RSBW2B3D.cjs +126 -0
- package/dist/chunk-RSBW2B3D.cjs.map +1 -0
- package/dist/chunk-RTFJ32T5.js +2635 -0
- package/dist/chunk-RTFJ32T5.js.map +1 -0
- package/dist/chunk-SFVEQ2T5.cjs +438 -0
- package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
- package/dist/chunk-SZT36SGB.cjs +154 -0
- package/dist/chunk-SZT36SGB.cjs.map +1 -0
- package/dist/chunk-TI24L4XE.cjs.map +1 -1
- package/dist/chunk-ULQXD4YZ.cjs +116 -0
- package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
- package/dist/chunk-VYHJX54R.js +126 -0
- package/dist/chunk-VYHJX54R.js.map +1 -0
- package/dist/cli/db-runner.cjs +497 -0
- package/dist/cli/db-runner.cjs.map +1 -0
- package/dist/cli/db-runner.d.cts +2 -0
- package/dist/cli/db-runner.d.ts +2 -0
- package/dist/cli/db-runner.js +497 -0
- package/dist/cli/db-runner.js.map +1 -0
- package/dist/cli/index.cjs +447 -69
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +473 -95
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +232 -0
- package/dist/docs/api-reference/compose.md +78 -0
- package/dist/docs/api-reference/db.md +351 -0
- package/dist/docs/api-reference/http-error.md +109 -0
- package/dist/docs/api-reference/ignite.md +323 -0
- package/dist/docs/api-reference/table.md +250 -0
- package/dist/docs/api-reference/tasks.md +140 -0
- package/dist/docs/cli/db.md +38 -0
- package/dist/docs/cli/diagnostics.md +145 -0
- package/dist/docs/cli/generate.md +120 -0
- package/dist/docs/cli/index.md +48 -0
- package/dist/docs/cli/start.md +112 -0
- package/dist/docs/contributing/index.md +139 -0
- package/dist/docs/core-concepts/background-tasks.md +228 -0
- package/dist/docs/core-concepts/clustering.md +114 -0
- package/dist/docs/core-concepts/file-based-routing.md +235 -0
- package/dist/docs/core-concepts/index.md +79 -0
- package/dist/docs/core-concepts/middleware.md +144 -0
- package/dist/docs/getting-started/index.md +91 -0
- package/dist/docs/getting-started/project-structure.md +154 -0
- package/dist/docs/guides/ai-agents.md +48 -0
- package/dist/docs/guides/authentication.md +196 -0
- package/dist/docs/guides/caching.md +124 -0
- package/dist/docs/guides/database.md +217 -0
- package/dist/docs/guides/deployment.md +171 -0
- package/dist/docs/guides/environment-variables.md +106 -0
- package/dist/docs/guides/error-handling.md +172 -0
- package/dist/docs/guides/generated-portals.md +115 -0
- package/dist/docs/guides/logging.md +70 -0
- package/dist/docs/guides/mailer.md +166 -0
- package/dist/docs/guides/migrations.md +106 -0
- package/dist/docs/guides/rbac.md +89 -0
- package/dist/docs/guides/validation.md +95 -0
- package/dist/docs/index.md +93 -0
- package/dist/docs/skills/SKILL.md +44 -0
- package/dist/docs/skills/api-surface.md +308 -0
- package/dist/docs/skills/auth-internals.md +141 -0
- package/dist/docs/skills/pre-flight.md +142 -0
- package/dist/docs/skills/routing-rules.md +114 -0
- package/dist/docs/skills/tasks-internals.md +172 -0
- package/dist/docs/skills/what-not-to-invent.md +251 -0
- package/dist/index.cjs +289 -391
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +472 -7
- package/dist/index.d.ts +472 -7
- package/dist/index.js +283 -385
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
- package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
- package/dist/pgboss-backend-UUJOVEYK.js +14 -0
- package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/types-DJCPAsM4.d.cts +541 -0
- package/dist/types-DJCPAsM4.d.ts +541 -0
- package/package.json +28 -5
- package/dist/chunk-6522HS2J.cjs +0 -99
- package/dist/chunk-6522HS2J.cjs.map +0 -1
- package/dist/chunk-DGVOJNR6.cjs +0 -55
- package/dist/chunk-DGVOJNR6.cjs.map +0 -1
- package/dist/chunk-KOHLLUN7.js +0 -55
- package/dist/chunk-KOHLLUN7.js.map +0 -1
- package/dist/chunk-VIP3PFWZ.js +0 -99
- package/dist/chunk-VIP3PFWZ.js.map +0 -1
- package/dist/types-BusbSenn.d.cts +0 -162
- package/dist/types-BusbSenn.d.ts +0 -162
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/index.ts","../../src/cli/commands/start.ts","../../src/cli/commands/build.ts","../../src/cli/commands/run.ts","../../src/cli/commands/generate.ts","../../src/cli/commands/diagnostics.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { startCommand } from './commands/start.js';\nimport { buildCommand } from './commands/build.js';\nimport { runCommand } from './commands/run.js';\nimport { generateCommand } from './commands/generate.js';\nimport { diagnosticsCommands } from './commands/diagnostics.js';\n\nconst program = new Command('efc').description('Express File Cluster CLI').version('0.1.0');\n\nprogram.addCommand(startCommand());\nprogram.addCommand(buildCommand());\nprogram.addCommand(runCommand());\nprogram.addCommand(generateCommand());\n\nfor (const cmd of diagnosticsCommands()) {\n program.addCommand(cmd);\n}\n\nprogram.parse(process.argv);\n","import { Command } from 'commander';\nimport { spawn } from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport pc from 'picocolors';\n\nexport function startCommand(): Command {\n const cmd = new Command('start');\n\n cmd\n .argument('<mode>', 'dev | prod')\n .description('Start the EFC server')\n .action((mode: string) => {\n if (mode === 'dev') {\n startDev();\n } else if (mode === 'prod') {\n startProd();\n } else {\n console.error(pc.red(`Unknown mode: ${mode}. Use 'dev' or 'prod'.`));\n process.exit(1);\n }\n });\n\n return cmd;\n}\n\n// tsx watch restarts the entry module in place rather than spawning a brand-new OS process\n// per change, so process.env itself persists (with its mutations) across restarts. A preload\n// that re-reads .env on every restart therefore can't just do \"only set if currently unset\" —\n// by the second restart, every key it set last time already looks \"currently set\" and a\n// naive check would treat a prior injection the same as a real OS-exported var, freezing\n// stale values forever. Instead it tracks which keys IT injected (via a marker env var) so\n// its own previous writes are always safe to overwrite, while true external env vars — never\n// present in that marker — still win, same as before.\nfunction writeDevEnvPreload(cwd: string): string {\n const cacheDir = path.join(cwd, 'node_modules', '.cache', 'efc');\n fs.mkdirSync(cacheDir, { recursive: true });\n const preloadPath = path.join(cacheDir, 'dev-env-preload.mjs');\n const source = `// Auto-generated by \\`efc start dev\\` — re-reads .env fresh on every restart\n// so tsx watch restarts always pick up the latest .env, instead of reusing a stale snapshot.\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nconst MARKER = '__EFC_DOTENV_KEYS__';\nconst previouslyInjected = new Set((process.env[MARKER] ?? '').split(',').filter(Boolean));\nconst injectedNow = [];\n\nconst envFile = path.join(process.cwd(), '.env');\nif (fs.existsSync(envFile)) {\n for (const line of fs.readFileSync(envFile, 'utf8').split('\\\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).trim();\n const raw = trimmed.slice(eq + 1).trim();\n // A key we injected on a previous restart is always safe to refresh; a key we've never\n // injected and that's already set is a real external env var, which still wins.\n if (previouslyInjected.has(key) || process.env[key] === undefined) {\n process.env[key] = raw.replace(/^(['\"])(.*)\\\\1$/, '$2');\n injectedNow.push(key);\n }\n }\n}\nprocess.env[MARKER] = injectedNow.join(',');\n`;\n fs.writeFileSync(preloadPath, source);\n return preloadPath;\n}\n\nfunction startDev(): void {\n const entry = resolveEntry();\n if (!entry) {\n console.error(pc.red('[EFC] Could not find entry point. Expected src/index.ts or index.ts'));\n process.exit(1);\n }\n\n console.log(pc.cyan('[EFC] Starting development server…'));\n console.log(pc.dim(` Entry: ${entry}`));\n console.log(pc.dim(' .env is re-read fresh on every restart (no need to stop/restart `efc start dev` for .env changes to take effect)'));\n\n const cwd = process.cwd();\n // Walk up from cwd looking for tsx in node_modules/.bin (handles workspace hoisting)\n function findTsx(): string {\n let dir = cwd;\n while (true) {\n const candidate = path.join(dir, 'node_modules', '.bin', 'tsx');\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) return 'tsx'; // reached filesystem root, fall back to PATH\n dir = parent;\n }\n }\n const tsx = findTsx();\n const preloadPath = writeDevEnvPreload(cwd);\n\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n // Always last: `efc start dev` must force development mode even if the\n // parent shell/CI already exports NODE_ENV=production, otherwise ignite()'s\n // cluster default (`NODE_ENV === 'production'`) silently enables clustering\n // in what's supposed to be a single-process dev server.\n NODE_ENV: 'development',\n NODE_OPTIONS: [process.env['NODE_OPTIONS'], `--import ${preloadPath}`]\n .filter(Boolean)\n .join(' '),\n };\n\n const child = spawn(tsx, ['watch', '--include', 'src', entry], { stdio: 'inherit', env });\n child.on('exit', (code) => process.exit(code ?? 0));\n}\n\nfunction startProd(): void {\n const cwd = process.cwd();\n const distEntry = path.join(cwd, 'dist', 'index.js');\n\n if (!fs.existsSync(distEntry)) {\n console.error(pc.red('[EFC] dist/index.js not found. Run `efc build prod` first.'));\n process.exit(1);\n }\n\n console.log(pc.cyan('[EFC] Starting production server…'));\n\n // Production env comes exclusively from process.env — no .env file loading.\n // Platforms (Docker, Kubernetes, Railway, Heroku, etc.) inject vars directly.\n const child = spawn('node', [distEntry], {\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'production' },\n });\n child.on('exit', (code) => process.exit(code ?? 0));\n}\n\nfunction resolveEntry(): string | null {\n const cwd = process.cwd();\n const candidates = [\n path.join(cwd, 'src', 'index.ts'),\n path.join(cwd, 'index.ts'),\n path.join(cwd, 'src', 'index.js'),\n path.join(cwd, 'index.js'),\n ];\n return candidates.find((f) => fs.existsSync(f)) ?? null;\n}\n","import { Command } from 'commander';\nimport { spawn } from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport pc from 'picocolors';\n\nexport function buildCommand(): Command {\n const cmd = new Command('build');\n\n cmd\n .argument('<mode>', 'prod')\n .description('Build the application for production')\n .action((mode: string) => {\n if (mode !== 'prod') {\n console.error(pc.red(`Unknown build mode: ${mode}. Use 'prod'.`));\n process.exit(1);\n }\n buildProd();\n });\n\n return cmd;\n}\n\nfunction findBin(name: string): string {\n let dir = process.cwd();\n while (true) {\n const candidate = path.join(dir, 'node_modules', '.bin', name);\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) return name; // fell off root, hope it's on PATH\n dir = parent;\n }\n}\n\nfunction resolveEntry(): string | null {\n const cwd = process.cwd();\n const candidates = [\n path.join(cwd, 'src', 'index.ts'),\n path.join(cwd, 'index.ts'),\n path.join(cwd, 'src', 'index.js'),\n path.join(cwd, 'index.js'),\n ];\n return candidates.find((f) => fs.existsSync(f)) ?? null;\n}\n\nfunction hasTsupConfig(): boolean {\n const cwd = process.cwd();\n return ['tsup.config.ts', 'tsup.config.js', 'tsup.config.mjs', 'tsup.config.cjs'].some((f) =>\n fs.existsSync(path.join(cwd, f)),\n );\n}\n\nfunction findTsConfig(): string | null {\n const cwd = process.cwd();\n const tsconfig = path.join(cwd, 'tsconfig.json');\n return fs.existsSync(tsconfig) ? tsconfig : null;\n}\n\nfunction buildProd(): void {\n console.log(pc.cyan('[EFC] Building for production…'));\n\n const tsconfig = findTsConfig();\n if (!tsconfig) {\n console.error(pc.red('[EFC] No tsconfig.json found in the current directory.'));\n process.exit(1);\n }\n\n const tsc = spawn(findBin('tsc'), ['--noEmit', '--project', tsconfig], { stdio: 'inherit' });\n\n tsc.on('exit', (code) => {\n if (code !== 0) {\n console.error(pc.red('[EFC] TypeScript errors found. Fix them before building.'));\n process.exit(1);\n }\n\n let tsupArgs: string[];\n if (hasTsupConfig()) {\n tsupArgs = [];\n } else {\n const entry = resolveEntry();\n if (!entry) {\n console.error(\n pc.red('[EFC] Could not find entry point. Expected src/index.ts or index.ts'),\n );\n process.exit(1);\n return;\n }\n tsupArgs = [entry, '--format', 'cjs,esm', '--clean', '--target', 'node18'];\n }\n\n const tsup = spawn(findBin('tsup'), tsupArgs, { stdio: 'inherit' });\n tsup.on('exit', (tsupCode) => {\n if (tsupCode === 0) {\n console.log(pc.green('[EFC] Build complete → dist/'));\n } else {\n process.exit(tsupCode ?? 1);\n }\n });\n });\n}\n","import { Command } from 'commander';\nimport { spawn } from 'node:child_process';\nimport pc from 'picocolors';\n\nexport function runCommand(): Command {\n const cmd = new Command('run');\n\n cmd\n .argument('<runner>', 'tests')\n .description('Run EFC sub-commands (tests)')\n .allowUnknownOption()\n .action((runner: string) => {\n if (runner === 'tests') {\n runTests(cmd.args.slice(1));\n } else {\n console.error(pc.red(`Unknown runner: ${runner}. Use 'tests'.`));\n process.exit(1);\n }\n });\n\n return cmd;\n}\n\nfunction runTests(extraArgs: string[]): void {\n console.log(pc.cyan('[EFC] Running tests via Vitest…'));\n const child = spawn('npx', ['vitest', 'run', ...extraArgs], { stdio: 'inherit' });\n child.on('exit', (code) => process.exit(code ?? 0));\n}\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport pc from 'picocolors';\n\nexport function generateCommand(): Command {\n const cmd = new Command('generate').alias('g').description('Scaffold EFC modules');\n\n cmd\n .command('route <routePath>')\n .description('Scaffold a route module, e.g. users/[id]')\n .action((routePath: string) => generateRoute(routePath));\n\n cmd\n .command('task <name>')\n .description('Scaffold a background task module')\n .action((name: string) => generateTask(name));\n\n cmd\n .command('middleware <name>')\n .description('Scaffold a middleware module')\n .action((name: string) => generateMiddleware(name));\n\n return cmd;\n}\n\nfunction writeFile(filePath: string, content: string): void {\n const dir = path.dirname(filePath);\n fs.mkdirSync(dir, { recursive: true });\n if (fs.existsSync(filePath)) {\n console.error(pc.red(`File already exists: ${filePath}`));\n process.exit(1);\n }\n fs.writeFileSync(filePath, content, 'utf8');\n console.log(pc.green(` created ${path.relative(process.cwd(), filePath)}`));\n}\n\nfunction generateRoute(routePath: string): void {\n const cwd = process.cwd();\n const filePath = path.join(cwd, 'src', 'api', `${routePath}.ts`);\n const content = `import type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'TODO: describe this endpoint.',\n request: {\n headers: {\n // 'Content-Type': 'application/json'\n },\n query: {\n // search: 'query'\n },\n },\n response: {\n status: 200,\n body: {\n message: 'OK'\n }\n }\n },\n POST: {\n description: 'TODO: describe this endpoint.',\n request: {\n body: {\n // name: 'string'\n }\n },\n response: {\n status: 201,\n body: {\n message: 'Created'\n }\n }\n }\n};\n\nexport const GET = async (req: Request, res: Response) => {\n res.json({ message: 'OK' });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n res.status(201).json({ message: 'Created' });\n};\n`;\n\n writeFile(filePath, content);\n console.log(pc.cyan(`[EFC] Route scaffolded`));\n}\n\nfunction generateTask(name: string): void {\n const cwd = process.cwd();\n const filePath = path.join(cwd, 'src', 'tasks', `${name}.ts`);\n\n const content = `import { defineTask } from 'express-file-cluster/tasks';\n\ninterface ${name}Payload {\n // TODO: define payload fields\n}\n\nexport default defineTask<${name}Payload>(async (payload) => {\n // TODO: implement task logic\n console.log('[Task:${name}]', payload);\n});\n`;\n\n writeFile(filePath, content);\n console.log(pc.cyan(`[EFC] Task scaffolded`));\n}\n\nfunction generateMiddleware(name: string): void {\n const cwd = process.cwd();\n const filePath = path.join(cwd, 'src', 'middlewares', `${name}.ts`);\n\n const content = `import type { Request, Response, NextFunction } from 'express';\n\nexport function ${name}(req: Request, res: Response, next: NextFunction): void {\n // TODO: implement middleware logic\n next();\n}\n`;\n\n writeFile(filePath, content);\n console.log(pc.cyan(`[EFC] Middleware scaffolded`));\n}\n","import { Command } from 'commander';\nimport { scanDir } from '../../router/scan.js';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport pc from 'picocolors';\n\nexport function diagnosticsCommands(): Command[] {\n return [routesCommand(), tasksCommand(), doctorCommand()];\n}\n\nfunction routesCommand(): Command {\n return new Command('routes').description('Print the resolved route table').action(() => {\n const apiDir = resolveApiDir();\n if (!apiDir) {\n console.error(pc.red('[EFC] Could not find apiDir (expected src/api)'));\n process.exit(1);\n }\n\n const routes = scanDir(apiDir);\n if (routes.length === 0) {\n console.log(pc.yellow('No routes found.'));\n return;\n }\n\n console.log(pc.bold('\\n Route Table\\n'));\n console.log(pc.dim(' ' + '─'.repeat(60)));\n for (const route of routes) {\n const rel = path.relative(process.cwd(), route.filePath);\n console.log(` ${pc.cyan(route.urlPath.padEnd(35))} ${pc.dim(rel)}`);\n }\n console.log(pc.dim(' ' + '─'.repeat(60)));\n console.log(pc.dim(`\\n ${routes.length} route(s) found\\n`));\n });\n}\n\nfunction tasksCommand(): Command {\n return new Command('tasks').description('List registered background tasks').action(() => {\n const tasksDir = resolveTasksDir();\n if (!tasksDir || !fs.existsSync(tasksDir)) {\n console.log(pc.yellow('No tasks directory found.'));\n return;\n }\n\n const files = fs.readdirSync(tasksDir).filter((f) => /\\.(ts|js)$/.test(f));\n if (files.length === 0) {\n console.log(pc.yellow('No tasks found.'));\n return;\n }\n\n console.log(pc.bold('\\n Background Tasks\\n'));\n for (const file of files) {\n console.log(` ${pc.cyan(path.basename(file, path.extname(file)))}`);\n }\n console.log();\n });\n}\n\n// `efc doctor` runs as a standalone CLI invocation — nothing has loaded .env into\n// process.env yet (that only happens inside `efc start dev`'s spawned child process).\n// Parse .env directly so vars that only live there, not in the shell, are still seen.\nfunction readEnvFile(cwd: string): Record<string, string> {\n const envPath = path.join(cwd, '.env');\n if (!fs.existsSync(envPath)) return {};\n\n const vars: Record<string, string> = {};\n for (const line of fs.readFileSync(envPath, 'utf8').split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).trim();\n const raw = trimmed.slice(eq + 1).trim();\n vars[key] = raw.replace(/^(['\"])(.*)\\1$/, '$2');\n }\n return vars;\n}\n\nfunction doctorCommand(): Command {\n return new Command('doctor')\n .description('Validate config, env vars, and project setup')\n .action(() => {\n const cwd = process.cwd();\n const envFileVars = readEnvFile(cwd);\n const hasEnvVar = (key: string): boolean =>\n Boolean(process.env[key]) || Boolean(envFileVars[key]);\n\n const checks: { label: string; ok: boolean; hint?: string }[] = [\n {\n label: 'package.json exists',\n ok: fs.existsSync(path.join(cwd, 'package.json')),\n },\n {\n label: 'tsconfig.json exists',\n ok: fs.existsSync(path.join(cwd, 'tsconfig.json')),\n hint: 'Run `tsc --init` to create one',\n },\n {\n label: 'src/api directory exists',\n ok: fs.existsSync(path.join(cwd, 'src', 'api')),\n hint: 'Create src/api/ and add route files',\n },\n {\n label: 'DATABASE_URL set',\n ok: hasEnvVar('DATABASE_URL'),\n hint: 'Add DATABASE_URL to .env',\n },\n {\n label: 'JWT_SECRET set',\n ok: hasEnvVar('JWT_SECRET'),\n hint: 'Add JWT_SECRET to .env (generate: openssl rand -hex 64)',\n },\n ];\n\n console.log(pc.bold('\\n EFC Doctor\\n'));\n let allOk = true;\n for (const check of checks) {\n const icon = check.ok ? pc.green('✓') : pc.red('✗');\n console.log(` ${icon} ${check.label}`);\n if (!check.ok) {\n allOk = false;\n if (check.hint) console.log(pc.dim(` → ${check.hint}`));\n }\n }\n console.log();\n if (allOk) {\n console.log(pc.green(' All checks passed!\\n'));\n } else {\n console.log(pc.yellow(' Some checks failed. Fix the issues above.\\n'));\n process.exit(1);\n }\n });\n}\n\nfunction resolveApiDir(): string | null {\n const cwd = process.cwd();\n const candidates = [path.join(cwd, 'src', 'api'), path.join(cwd, 'api')];\n return candidates.find((d) => fs.existsSync(d)) ?? null;\n}\n\nfunction resolveTasksDir(): string | null {\n const cwd = process.cwd();\n const candidates = [path.join(cwd, 'src', 'tasks'), path.join(cwd, 'tasks')];\n return candidates.find((d) => fs.existsSync(d)) ?? null;\n}\n"],"mappings":";;;;;;AACA,SAAS,WAAAA,gBAAe;;;ACDxB,SAAS,eAAe;AACxB,SAAS,aAAa;AACtB,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,OAAO,QAAQ;AAER,SAAS,eAAwB;AACtC,QAAM,MAAM,IAAI,QAAQ,OAAO;AAE/B,MACG,SAAS,UAAU,YAAY,EAC/B,YAAY,sBAAsB,EAClC,OAAO,CAAC,SAAiB;AACxB,QAAI,SAAS,OAAO;AAClB,eAAS;AAAA,IACX,WAAW,SAAS,QAAQ;AAC1B,gBAAU;AAAA,IACZ,OAAO;AACL,cAAQ,MAAM,GAAG,IAAI,iBAAiB,IAAI,wBAAwB,CAAC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AK,CAAC,MAAMC,IAAG,WAAW,CAAC,CAAC,KAAK;AACrD;AAEA,SAAS,kBAAiC;AACxC,QAAM,MAAM,QAAQ,IAAI;AACxB,QAAM,aAAa,CAACD,MAAK,KAAK,KAAK,OAAO,OAAO,GAAGA,MAAK,KAAK,KAAK,OAAO,CAAC;AAC3E,SAAO,WAAW,KAAK,CAAC,MAAMC,IAAG,WAAW,CAAC,CAAC,KAAK;AACrD;;;ALvIA,IAAM,UAAU,IAAIG,SAAQ,KAAK,EAAE,YAAY,0BAA0B,EAAE,QAAQ,OAAO;AAE1F,QAAQ,WAAW,aAAa,CAAC;AACjC,QAAQ,WAAW,aAAa,CAAC;AACjC,QAAQ,WAAW,WAAW,CAAC;AAC/B,QAAQ,WAAW,gBAAgB,CAAC;AAEpC,WAAW,OAAO,oBAAoB,GAAG;AACvC,UAAQ,WAAW,GAAG;AACxB;AAEA,QAAQ,MAAM,QAAQ,IAAI;","names":["Command","Command","spawn","path","fs","pc","resolveEntry","Command","spawn","pc","Command","fs","path","pc","Command","path","fs","pc","Command","Command"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/index.ts","../../src/cli/commands/start.ts","../../src/cli/commands/build.ts","../../src/cli/commands/run.ts","../../src/cli/commands/generate.ts","../../src/cli/commands/diagnostics.ts","../../src/cli/env.ts","../../src/cli/commands/task-admin.ts","../../src/tasks/admin.ts","../../src/cli/commands/db.ts"],"sourcesContent":["#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { Command } from 'commander';\nimport { startCommand } from './commands/start.js';\nimport { buildCommand } from './commands/build.js';\nimport { runCommand } from './commands/run.js';\nimport { generateCommand } from './commands/generate.js';\nimport { diagnosticsCommands } from './commands/diagnostics.js';\nimport { dbCommand } from './commands/db.js';\n\n// package.json sits two levels up from both src/cli/index.ts and dist/cli/index.js.\nconst { version } = JSON.parse(\n fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8'),\n) as { version: string };\n\n// A globally installed `efc` must not run a project's commands itself: it would resolve\n// drivers (mongoose, pg, ...) from the global install and load a second copy of the\n// framework alongside the project's own. If the project has its own express-file-cluster,\n// hand the whole invocation to that copy — same as eslint, jest and friends do.\nfunction localCli(): string | undefined {\n if (process.env['EFC_CLI_DELEGATED']) return undefined;\n const self = fs.realpathSync(fileURLToPath(new URL('../..', import.meta.url)));\n for (let dir = process.cwd(); ; dir = path.dirname(dir)) {\n const pkgDir = path.join(dir, 'node_modules', 'express-file-cluster');\n if (fs.existsSync(path.join(pkgDir, 'package.json'))) {\n const real = fs.realpathSync(pkgDir);\n const cli = path.join(real, 'dist', 'cli', 'index.js');\n return real !== self && fs.existsSync(cli) ? cli : undefined;\n }\n if (path.dirname(dir) === dir) return undefined;\n }\n}\n\nconst delegate = localCli();\nif (delegate) {\n const child = spawn(process.execPath, [delegate, ...process.argv.slice(2)], {\n stdio: 'inherit',\n env: { ...process.env, EFC_CLI_DELEGATED: '1' },\n });\n for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => child.kill(signal));\n child.on('exit', (code, signal) => process.exit(code ?? (signal ? 1 : 0)));\n} else {\n run();\n}\n\nfunction run(): void {\n const program = new Command('efc').description('Express File Cluster CLI').version(version);\n\n program.addCommand(startCommand());\n program.addCommand(buildCommand());\n program.addCommand(runCommand());\n program.addCommand(generateCommand());\n program.addCommand(dbCommand());\n\n for (const cmd of diagnosticsCommands()) {\n program.addCommand(cmd);\n }\n\n program.parse(process.argv);\n}\n","import { Command } from 'commander';\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport pc from 'picocolors';\n\nexport function startCommand(): Command {\n const cmd = new Command('start');\n\n cmd\n .argument('<mode>', 'dev | prod')\n .description('Start the EFC server')\n .action((mode: string) => {\n if (mode === 'dev') {\n startDev();\n } else if (mode === 'prod') {\n startProd();\n } else {\n console.error(pc.red(`Unknown mode: ${mode}. Use 'dev' or 'prod'.`));\n process.exit(1);\n }\n });\n\n return cmd;\n}\n\n// tsx watch restarts the entry module in place rather than spawning a brand-new OS process\n// per change, so process.env itself persists (with its mutations) across restarts. A preload\n// that re-reads .env on every restart therefore can't just do \"only set if currently unset\" —\n// by the second restart, every key it set last time already looks \"currently set\" and a\n// naive check would treat a prior injection the same as a real OS-exported var, freezing\n// stale values forever. Instead it tracks which keys IT injected (via a marker env var) so\n// its own previous writes are always safe to overwrite, while true external env vars — never\n// present in that marker — still win, same as before.\nfunction writeDevEnvPreload(cwd: string): string {\n const cacheDir = path.join(cwd, 'node_modules', '.cache', 'efc');\n fs.mkdirSync(cacheDir, { recursive: true });\n const preloadPath = path.join(cacheDir, 'dev-env-preload.mjs');\n const source = `// Auto-generated by \\`efc start dev\\` — re-reads .env fresh on every restart\n// so tsx watch restarts always pick up the latest .env, instead of reusing a stale snapshot.\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nconst MARKER = '__EFC_DOTENV_KEYS__';\nconst previouslyInjected = new Set((process.env[MARKER] ?? '').split(',').filter(Boolean));\nconst injectedNow = [];\n\nconst envFile = path.join(process.cwd(), '.env');\nif (fs.existsSync(envFile)) {\n for (const line of fs.readFileSync(envFile, 'utf8').split('\\\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).trim();\n const raw = trimmed.slice(eq + 1).trim();\n // A key we injected on a previous restart is always safe to refresh; a key we've never\n // injected and that's already set is a real external env var, which still wins.\n if (previouslyInjected.has(key) || process.env[key] === undefined) {\n process.env[key] = raw.replace(/^(['\"])(.*)\\\\1$/, '$2');\n injectedNow.push(key);\n }\n }\n}\nprocess.env[MARKER] = injectedNow.join(',');\n`;\n fs.writeFileSync(preloadPath, source);\n return preloadPath;\n}\n\nfunction startDev(): void {\n const entry = resolveEntry();\n if (!entry) {\n console.error(pc.red('[EFC] Could not find entry point. Expected src/index.ts or index.ts'));\n process.exit(1);\n }\n\n console.log(pc.cyan('[EFC] Starting development server…'));\n console.log(pc.dim(` Entry: ${entry}`));\n console.log(\n pc.dim(\n ' .env is re-read fresh on every restart (no need to stop/restart `efc start dev` for .env changes to take effect)',\n ),\n );\n\n const cwd = process.cwd();\n // Walk up from cwd looking for tsx in node_modules/.bin (handles workspace hoisting)\n function findTsx(): string | undefined {\n let dir = cwd;\n while (true) {\n const candidate = path.join(dir, 'node_modules', '.bin', 'tsx');\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n }\n const tsx = findTsx();\n const isJs = /\\.(m?js|cjs)$/.test(entry);\n if (!tsx && !isJs) {\n console.error(\n pc.red('[EFC] tsx is required to run TypeScript in development. Run: npm install -D tsx'),\n );\n process.exit(1);\n }\n const preloadPath = writeDevEnvPreload(cwd);\n\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n // Always last: `efc start dev` must force development mode even if the\n // parent shell/CI already exports NODE_ENV=production, otherwise ignite()'s\n // cluster default (`NODE_ENV === 'production'`) silently enables clustering\n // in what's supposed to be a single-process dev server.\n NODE_ENV: 'development',\n NODE_OPTIONS: [process.env['NODE_OPTIONS'], `--import ${preloadPath}`]\n .filter(Boolean)\n .join(' '),\n };\n\n // JavaScript projects don't install tsx: Node's own watch mode restarts on changes in src/.\n const child = tsx\n ? spawn(tsx, ['watch', '--include', 'src', entry], { stdio: 'inherit', env })\n : spawn(process.execPath, ['--watch', '--watch-path', path.join(cwd, 'src'), entry], {\n stdio: 'inherit',\n env,\n });\n forwardSignals(child);\n}\n\n// This CLI is often PID 1's direct child (`npm start`, `CMD [\"npx\", \"efc\", ...]`), so a\n// stop signal lands here, not on the server. Relay it so the app's gracefulShutdown runs,\n// and mirror the child's exit status instead of reporting success for a crash.\nfunction forwardSignals(child: ChildProcess): void {\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.on(signal, () => child.kill(signal));\n }\n child.on('exit', (code, signal) => process.exit(code ?? (signal ? 1 : 0)));\n}\n\nfunction startProd(): void {\n const cwd = process.cwd();\n // `efc build prod` mirrors the source tree (dist/src/index.js); dist/index.js covers\n // projects that build with their own tsup.config.\n const distEntry = [\n path.join(cwd, 'dist', 'src', 'index.js'),\n path.join(cwd, 'dist', 'index.js'),\n ].find((f) => fs.existsSync(f));\n\n if (!distEntry) {\n console.error(pc.red('[EFC] dist/src/index.js not found. Run `efc build prod` first.'));\n process.exit(1);\n }\n\n console.log(pc.cyan('[EFC] Starting production server…'));\n\n // Production env comes exclusively from process.env — no .env file loading.\n // Platforms (Docker, Kubernetes, Railway, Heroku, etc.) inject vars directly.\n const child = spawn('node', [distEntry], {\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'production' },\n });\n forwardSignals(child);\n}\n\nfunction resolveEntry(): string | null {\n const cwd = process.cwd();\n const candidates = [\n path.join(cwd, 'src', 'index.ts'),\n path.join(cwd, 'index.ts'),\n path.join(cwd, 'src', 'index.js'),\n path.join(cwd, 'index.js'),\n ];\n return candidates.find((f) => fs.existsSync(f)) ?? null;\n}\n","import { Command } from 'commander';\nimport { spawn } from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport pc from 'picocolors';\n\nexport function buildCommand(): Command {\n const cmd = new Command('build');\n\n cmd\n .argument('<mode>', 'prod')\n .description('Build the application for production')\n .action((mode: string) => {\n if (mode !== 'prod') {\n console.error(pc.red(`Unknown build mode: ${mode}. Use 'prod'.`));\n process.exit(1);\n }\n buildProd();\n });\n\n return cmd;\n}\n\nfunction findBin(name: string): string {\n let dir = process.cwd();\n while (true) {\n const candidate = path.join(dir, 'node_modules', '.bin', name);\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) return name; // fell off root, hope it's on PATH\n dir = parent;\n }\n}\n\n// Routes and tasks are discovered by scanning the filesystem at runtime, so bundling\n// from src/index.ts would leave them out of dist/ entirely (and bundling each file would\n// duplicate shared modules like models). Instead every source file is transpiled 1:1:\n// src/api/users.ts → dist/src/api/users.js, with efc.config.ts → dist/efc.config.js.\n// tsup's CLI can't turn bundling off, so the config is generated per build.\nfunction writeAppTsupConfig(cwd: string): string {\n const pkgPath = path.join(cwd, 'package.json');\n const isEsm =\n fs.existsSync(pkgPath) &&\n (JSON.parse(fs.readFileSync(pkgPath, 'utf8')) as { type?: string }).type === 'module';\n const entry = [\n 'src/**/*.{ts,mts,js,mjs}',\n ...['efc.config.ts', 'efc.config.js'].filter((f) => fs.existsSync(path.join(cwd, f))),\n '!src/**/*.d.ts',\n '!src/**/*.test.*',\n '!src/**/__tests__/**',\n ];\n const config = `export default {\n entry: ${JSON.stringify(entry)},\n outDir: 'dist',\n format: ['${isEsm ? 'esm' : 'cjs'}'],\n bundle: false,\n splitting: false,\n clean: true,\n sourcemap: true,\n platform: 'node',\n target: 'node18',\n esbuildOptions(options) {\n options.outbase = '.';\n },\n};\n`;\n const configPath = path.join(cwd, 'node_modules', '.cache', 'efc', 'tsup.config.mjs');\n fs.mkdirSync(path.dirname(configPath), { recursive: true });\n fs.writeFileSync(configPath, config);\n return configPath;\n}\n\nfunction hasTsupConfig(): boolean {\n const cwd = process.cwd();\n return ['tsup.config.ts', 'tsup.config.js', 'tsup.config.mjs', 'tsup.config.cjs'].some((f) =>\n fs.existsSync(path.join(cwd, f)),\n );\n}\n\nfunction findTsConfig(): string | null {\n const cwd = process.cwd();\n const tsconfig = path.join(cwd, 'tsconfig.json');\n return fs.existsSync(tsconfig) ? tsconfig : null;\n}\n\nfunction buildProd(): void {\n console.log(pc.cyan('[EFC] Building for production…'));\n\n const tsconfig = findTsConfig();\n if (!tsconfig) {\n // JavaScript project — nothing to typecheck, but routes/tasks still need to land in dist/.\n transpile();\n return;\n }\n\n const tsc = spawn(findBin('tsc'), ['--noEmit', '--project', tsconfig], { stdio: 'inherit' });\n\n tsc.on('exit', (code) => {\n if (code !== 0) {\n console.error(pc.red('[EFC] TypeScript errors found. Fix them before building.'));\n process.exit(1);\n }\n transpile();\n });\n}\n\n// JavaScript projects need no transpiling (tsup can't even load without typescript\n// installed): mirror src/ and efc.config.js into dist/ with the same layout tsup\n// would produce, so `efc start prod` and `efc db --dist` find the same paths.\nfunction copyJsProject(cwd: string): void {\n const dist = path.join(cwd, 'dist');\n fs.rmSync(dist, { recursive: true, force: true });\n fs.cpSync(path.join(cwd, 'src'), path.join(dist, 'src'), {\n recursive: true,\n filter: (src) => !/(\\.test\\.[cm]?js$|[\\\\/]__tests__([\\\\/]|$))/.test(src),\n });\n for (const f of ['efc.config.js', 'efc.config.mjs']) {\n if (fs.existsSync(path.join(cwd, f))) fs.copyFileSync(path.join(cwd, f), path.join(dist, f));\n }\n console.log(pc.green('[EFC] Build complete → dist/ (JavaScript copied as-is)'));\n}\n\nfunction transpile(): void {\n let tsupArgs: string[];\n const cwd = process.cwd();\n if (hasTsupConfig()) {\n tsupArgs = [];\n } else {\n const hasTs = fs.existsSync(path.join(cwd, 'src', 'index.ts'));\n if (!hasTs && !fs.existsSync(path.join(cwd, 'src', 'index.js'))) {\n console.error(pc.red('[EFC] Could not find entry point. Expected src/index.ts'));\n process.exit(1);\n return;\n }\n if (!hasTs && !findTsConfig()) {\n copyJsProject(cwd);\n return;\n }\n tsupArgs = ['--config', writeAppTsupConfig(cwd)];\n }\n\n const tsup = spawn(findBin('tsup'), tsupArgs, { stdio: 'inherit' });\n tsup.on('exit', (tsupCode) => {\n if (tsupCode === 0) {\n console.log(pc.green('[EFC] Build complete → dist/'));\n } else {\n process.exit(tsupCode ?? 1);\n }\n });\n}\n","import { Command } from 'commander';\nimport { spawn } from 'node:child_process';\nimport pc from 'picocolors';\n\nexport function runCommand(): Command {\n const cmd = new Command('run');\n\n cmd\n .argument('<runner>', 'tests')\n .description('Run EFC sub-commands (tests)')\n .allowUnknownOption()\n .action((runner: string) => {\n if (runner === 'tests') {\n runTests(cmd.args.slice(1));\n } else {\n console.error(pc.red(`Unknown runner: ${runner}. Use 'tests'.`));\n process.exit(1);\n }\n });\n\n return cmd;\n}\n\nfunction runTests(extraArgs: string[]): void {\n console.log(pc.cyan('[EFC] Running tests via Vitest…'));\n const child = spawn('npx', ['vitest', 'run', ...extraArgs], { stdio: 'inherit' });\n child.on('exit', (code) => process.exit(code ?? 0));\n}\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport pc from 'picocolors';\n\nexport function generateCommand(): Command {\n const cmd = new Command('generate').alias('g').description('Scaffold EFC modules');\n\n cmd\n .command('route <routePath>')\n .description('Scaffold a route module, e.g. users/[id]')\n .action((routePath: string) => generateRoute(routePath));\n\n cmd\n .command('task <name>')\n .description('Scaffold a background task module')\n .action((name: string) => generateTask(name));\n\n cmd\n .command('middleware <name>')\n .description('Scaffold a middleware module')\n .action((name: string) => generateMiddleware(name));\n\n cmd\n .command('migration <name>')\n .description('Scaffold a timestamped migration in src/migrations')\n .action((name: string) => generateMigration(name));\n\n cmd\n .command('seed <name>')\n .description('Scaffold a seed script in src/seeds')\n .action((name: string) => generateSeed(name));\n\n return cmd;\n}\n\nfunction writeFile(filePath: string, content: string): void {\n const dir = path.dirname(filePath);\n fs.mkdirSync(dir, { recursive: true });\n if (fs.existsSync(filePath)) {\n console.error(pc.red(`File already exists: ${filePath}`));\n process.exit(1);\n }\n fs.writeFileSync(filePath, content, 'utf8');\n console.log(pc.green(` created ${path.relative(process.cwd(), filePath)}`));\n}\n\nfunction generateRoute(routePath: string): void {\n const cwd = process.cwd();\n const filePath = path.join(cwd, 'src', 'api', `${routePath}.ts`);\n const content = `import type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'TODO: describe this endpoint.',\n request: {\n headers: {\n // 'Content-Type': 'application/json'\n },\n query: {\n // search: 'query'\n },\n },\n response: {\n status: 200,\n body: {\n message: 'OK'\n }\n }\n },\n POST: {\n description: 'TODO: describe this endpoint.',\n request: {\n body: {\n // name: 'string'\n }\n },\n response: {\n status: 201,\n body: {\n message: 'Created'\n }\n }\n }\n};\n\nexport const GET = async (req: Request, res: Response) => {\n res.json({ message: 'OK' });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n res.status(201).json({ message: 'Created' });\n};\n`;\n\n writeFile(filePath, content);\n console.log(pc.cyan(`[EFC] Route scaffolded`));\n}\n\nfunction generateTask(name: string): void {\n const cwd = process.cwd();\n const filePath = path.join(cwd, 'src', 'tasks', `${name}.ts`);\n\n const content = `import { defineTask } from 'express-file-cluster/tasks';\n\ninterface ${name}Payload {\n // TODO: define payload fields\n}\n\nexport default defineTask<${name}Payload>(async (payload) => {\n // TODO: implement task logic\n console.log('[Task:${name}]', payload);\n});\n`;\n\n writeFile(filePath, content);\n console.log(pc.cyan(`[EFC] Task scaffolded`));\n}\n\nfunction generateMiddleware(name: string): void {\n const cwd = process.cwd();\n const filePath = path.join(cwd, 'src', 'middlewares', `${name}.ts`);\n\n const content = `import type { Request, Response, NextFunction } from 'express';\n\nexport function ${name}(req: Request, res: Response, next: NextFunction): void {\n // TODO: implement middleware logic\n next();\n}\n`;\n\n writeFile(filePath, content);\n console.log(pc.cyan(`[EFC] Middleware scaffolded`));\n}\n\nconst isTypeScript = () => fs.existsSync(path.join(process.cwd(), 'tsconfig.json'));\nconst snake = (name: string) =>\n name\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .replace(/^_|_$/g, '')\n .toLowerCase();\n\nfunction generateMigration(name: string): void {\n // UTC timestamp prefix keeps files sorted in creation order.\n const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14);\n const ts = isTypeScript();\n const filePath = path.join(\n process.cwd(),\n 'src',\n 'migrations',\n `${stamp}_${snake(name)}.${ts ? 'ts' : 'js'}`,\n );\n const typeImport = ts ? \"import type { MigrationContext } from 'express-file-cluster';\\n\" : '';\n const ctx = ts ? '{ db, engine }: MigrationContext' : '{ db, engine }';\n const ret = ts ? ': Promise<void>' : '';\n writeFile(\n filePath,\n `${typeImport}// import { User } from '../model/User.js';\n\n// \\`efc db migrate\\` runs up(); \\`efc db rollback\\` runs down(). \\`db\\` is the native client:\n// a mongoose Connection on MongoDB, a node-postgres Pool on PostgreSQL.\nexport async function up(${ctx})${ret} {\n // await User.sync(); // create the table/collection, new columns and indexes\n}\n\nexport async function down(${ctx})${ret} {\n // if (engine === 'postgresql') await db.query('DROP TABLE IF EXISTS users');\n}\n`,\n );\n console.log(pc.cyan('[EFC] Migration scaffolded — run `efc db migrate`'));\n}\n\nfunction generateSeed(name: string): void {\n const ts = isTypeScript();\n const filePath = path.join(process.cwd(), 'src', 'seeds', `${snake(name)}.${ts ? 'ts' : 'js'}`);\n const typeImport = ts ? \"import type { MigrationContext } from 'express-file-cluster';\\n\" : '';\n const ctx = ts ? '{ engine }: MigrationContext' : '{ engine }';\n writeFile(\n filePath,\n `${typeImport}// import { User } from '../model/User.js';\n\n// Run with \\`efc db seed\\` (all seeds) or \\`efc db seed ${snake(name)}\\`.\nexport default async function seed(${ctx}) {\n // await User.createMany([{ name: 'Ada', email: 'ada@example.com' }]);\n}\n`,\n );\n console.log(pc.cyan('[EFC] Seed scaffolded — run `efc db seed`'));\n}\n","import { Command } from 'commander';\nimport { scanDir } from '../../router/scan.js';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport pc from 'picocolors';\nimport { readEnvFile } from '../env.js';\nimport { taskAdminCommands } from './task-admin.js';\n\nexport function diagnosticsCommands(): Command[] {\n return [routesCommand(), tasksCommand(), doctorCommand()];\n}\n\nfunction routesCommand(): Command {\n return new Command('routes').description('Print the resolved route table').action(() => {\n const apiDir = resolveApiDir();\n if (!apiDir) {\n console.error(pc.red('[EFC] Could not find apiDir (expected src/api)'));\n process.exit(1);\n }\n\n const routes = scanDir(apiDir);\n if (routes.length === 0) {\n console.log(pc.yellow('No routes found.'));\n return;\n }\n\n console.log(pc.bold('\\n Route Table\\n'));\n console.log(pc.dim(' ' + '─'.repeat(60)));\n for (const route of routes) {\n const rel = path.relative(process.cwd(), route.filePath);\n console.log(` ${pc.cyan(route.urlPath.padEnd(35))} ${pc.dim(rel)}`);\n }\n console.log(pc.dim(' ' + '─'.repeat(60)));\n console.log(pc.dim(`\\n ${routes.length} route(s) found\\n`));\n });\n}\n\nfunction tasksCommand(): Command {\n const cmd = new Command('tasks').description(\n 'List background tasks, or inspect the dead-letter queue (failed | retry | purge)',\n );\n for (const sub of taskAdminCommands()) cmd.addCommand(sub);\n return cmd.action(() => {\n const tasksDir = resolveTasksDir();\n if (!tasksDir || !fs.existsSync(tasksDir)) {\n console.log(pc.yellow('No tasks directory found.'));\n return;\n }\n\n const files = fs.readdirSync(tasksDir).filter((f) => /\\.(ts|js)$/.test(f));\n if (files.length === 0) {\n console.log(pc.yellow('No tasks found.'));\n return;\n }\n\n console.log(pc.bold('\\n Background Tasks\\n'));\n for (const file of files) {\n console.log(` ${pc.cyan(path.basename(file, path.extname(file)))}`);\n }\n console.log();\n });\n}\n\nfunction doctorCommand(): Command {\n return new Command('doctor')\n .description('Validate config, env vars, and project setup')\n .action(() => {\n const cwd = process.cwd();\n const envFileVars = readEnvFile(cwd);\n const hasEnvVar = (key: string): boolean =>\n Boolean(process.env[key]) || Boolean(envFileVars[key]);\n\n const checks: { label: string; ok: boolean; hint?: string }[] = [\n {\n label: 'package.json exists',\n ok: fs.existsSync(path.join(cwd, 'package.json')),\n },\n {\n label: 'tsconfig.json exists',\n ok: fs.existsSync(path.join(cwd, 'tsconfig.json')),\n hint: 'Run `tsc --init` to create one',\n },\n {\n label: 'src/api directory exists',\n ok: fs.existsSync(path.join(cwd, 'src', 'api')),\n hint: 'Create src/api/ and add route files',\n },\n {\n label: 'DATABASE_URL set',\n ok: hasEnvVar('DATABASE_URL'),\n hint: 'Add DATABASE_URL to .env',\n },\n {\n label: 'JWT_SECRET set',\n ok: hasEnvVar('JWT_SECRET'),\n hint: 'Add JWT_SECRET to .env (generate: openssl rand -hex 64)',\n },\n ];\n\n console.log(pc.bold('\\n EFC Doctor\\n'));\n let allOk = true;\n for (const check of checks) {\n const icon = check.ok ? pc.green('✓') : pc.red('✗');\n console.log(` ${icon} ${check.label}`);\n if (!check.ok) {\n allOk = false;\n if (check.hint) console.log(pc.dim(` → ${check.hint}`));\n }\n }\n console.log();\n if (allOk) {\n console.log(pc.green(' All checks passed!\\n'));\n } else {\n console.log(pc.yellow(' Some checks failed. Fix the issues above.\\n'));\n process.exit(1);\n }\n });\n}\n\nfunction resolveApiDir(): string | null {\n const cwd = process.cwd();\n const candidates = [path.join(cwd, 'src', 'api'), path.join(cwd, 'api')];\n return candidates.find((d) => fs.existsSync(d)) ?? null;\n}\n\nfunction resolveTasksDir(): string | null {\n const cwd = process.cwd();\n const candidates = [path.join(cwd, 'src', 'tasks'), path.join(cwd, 'tasks')];\n return candidates.find((d) => fs.existsSync(d)) ?? null;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n// Standalone CLI invocations (`efc doctor`, `efc tasks failed`, `efc db ...`) run before\n// anything has loaded .env into process.env — that only happens inside `efc start dev`'s\n// spawned child. Parse .env directly so vars that only live there are still seen.\nexport function readEnvFile(cwd: string = process.cwd()): Record<string, string> {\n const envPath = path.join(cwd, '.env');\n if (!fs.existsSync(envPath)) return {};\n\n const vars: Record<string, string> = {};\n for (const line of fs.readFileSync(envPath, 'utf8').split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).trim();\n const raw = trimmed.slice(eq + 1).trim();\n vars[key] = raw.replace(/^(['\"])(.*)\\1$/, '$2');\n }\n return vars;\n}\n\n/** process.env wins over .env, matching how the dev server resolves them. */\nexport function envVar(key: string, cwd: string = process.cwd()): string | undefined {\n return process.env[key] || readEnvFile(cwd)[key] || undefined;\n}\n","import { Command } from 'commander';\nimport pc from 'picocolors';\nimport { envVar } from '../env.js';\nimport { bullmqAdmin, type TaskAdmin } from '../../tasks/admin.js';\n\ninterface AdminOpts {\n backend?: string;\n queue: string;\n redisUrl?: string;\n databaseUrl?: string;\n}\n\nfunction withConnectionOptions(cmd: Command): Command {\n return cmd\n .option(\n '--backend <backend>',\n 'bullmq | pg-boss (default: inferred from REDIS_URL / DATABASE_URL)',\n )\n .option('--queue <name>', 'queue name (tasks.queue in ignite())', 'efc')\n .option('--redis-url <url>', 'Redis URL for BullMQ (default: REDIS_URL)')\n .option('--database-url <url>', 'Postgres URL for pg-boss (default: DATABASE_URL)');\n}\n\nasync function connect(opts: AdminOpts): Promise<TaskAdmin> {\n const redisUrl = opts.redisUrl ?? envVar('REDIS_URL');\n const databaseUrl = opts.databaseUrl ?? envVar('DATABASE_URL');\n const backend =\n opts.backend ??\n (redisUrl ? 'bullmq' : databaseUrl?.startsWith('postgres') ? 'pg-boss' : 'bullmq');\n\n if (backend === 'bullmq') return bullmqAdmin(redisUrl ?? 'redis://localhost:6379', opts.queue);\n if (backend === 'pg-boss') {\n if (!databaseUrl) throw new Error('[EFC] pg-boss needs DATABASE_URL (or --database-url)');\n const { pgBossAdmin } = await import('../../tasks/pgboss-backend.js');\n return pgBossAdmin(databaseUrl, opts.queue);\n }\n throw new Error(`[EFC] Unknown task backend: ${backend}`);\n}\n\nasync function run(opts: AdminOpts, fn: (admin: TaskAdmin) => Promise<void>): Promise<void> {\n let admin: TaskAdmin | undefined;\n try {\n admin = await connect(opts);\n await fn(admin);\n } catch (err) {\n console.error(pc.red(err instanceof Error ? err.message : String(err)));\n process.exitCode = 1;\n } finally {\n await admin?.close().catch(() => {});\n }\n}\n\nfunction ids(list: string[], all: boolean | undefined): string[] | null {\n if (all) return [];\n if (list.length === 0) {\n console.error(pc.red('Pass job ids, or --all'));\n process.exitCode = 1;\n return null;\n }\n return list;\n}\n\nexport function taskAdminCommands(): Command[] {\n const failed = withConnectionOptions(\n new Command('failed').description('List jobs that exhausted their retries (dead-lettered)'),\n )\n .option('-n, --limit <n>', 'max jobs to show', '20')\n .option('--name <task>', 'only this task')\n .option('--json', 'print JSON')\n .action((opts: AdminOpts & { limit: string; name?: string; json?: boolean }) =>\n run(opts, async (admin) => {\n const jobs = await admin.listFailed({\n limit: Number(opts.limit),\n ...(opts.name !== undefined && { name: opts.name }),\n });\n if (opts.json) {\n console.log(JSON.stringify(jobs, null, 2));\n return;\n }\n const counts = await admin.counts();\n console.log(\n pc.bold('\\n Queue ') +\n pc.dim(\n Object.entries(counts)\n .map(([k, v]) => `${k}=${v}`)\n .join(' '),\n ) +\n '\\n',\n );\n if (jobs.length === 0) {\n console.log(pc.green(' No failed jobs.\\n'));\n return;\n }\n for (const job of jobs) {\n console.log(\n ` ${pc.red('✗')} ${pc.cyan(job.name)} ${pc.dim('#' + job.id)} ` +\n pc.dim(\n `attempts=${job.attempts}${job.failedAt ? ' ' + job.failedAt.toISOString() : ''}`,\n ),\n );\n console.log(` ${job.error}`);\n console.log(pc.dim(` data: ${JSON.stringify(job.data)}`));\n }\n console.log();\n }),\n );\n\n const retry = withConnectionOptions(\n new Command('retry').description('Re-queue failed jobs').argument('[ids...]', 'job ids'),\n )\n .option('--all', 'retry every failed job')\n .action((list: string[], opts: AdminOpts & { all?: boolean }) => {\n const selected = ids(list, opts.all);\n if (!selected) return;\n return run(opts, async (admin) => {\n console.log(pc.green(`Retried ${await admin.retry(selected)} job(s)`));\n });\n });\n\n const purge = withConnectionOptions(\n new Command('purge').description('Delete failed jobs').argument('[ids...]', 'job ids'),\n )\n .option('--all', 'delete every failed job')\n .action((list: string[], opts: AdminOpts & { all?: boolean }) => {\n const selected = ids(list, opts.all);\n if (!selected) return;\n return run(opts, async (admin) => {\n console.log(pc.green(`Removed ${await admin.purge(selected)} job(s)`));\n });\n });\n\n return [failed, retry, purge];\n}\n","import type * as BullMQNS from 'bullmq';\nimport { parseRedisUrl } from './bullmq-backend.js';\n\n/** A job that exhausted its retries (BullMQ's failed set / pg-boss's failed state). */\nexport interface FailedJob {\n id: string;\n name: string;\n data: unknown;\n error: string;\n attempts: number;\n failedAt: Date | undefined;\n}\n\n/**\n * Dead-letter inspection used by `efc tasks failed | retry | purge`. Connects on its\n * own (outside ignite()), so it works against a running app's queue from any shell.\n */\nexport interface TaskAdmin {\n counts(): Promise<Record<string, number>>;\n listFailed(opts: { limit: number; name?: string }): Promise<FailedJob[]>;\n /** Re-queues failed jobs (all when `ids` is empty). Returns how many were retried. */\n retry(ids: string[]): Promise<number>;\n /** Deletes failed jobs (all when `ids` is empty). Returns how many were removed. */\n purge(ids: string[]): Promise<number>;\n close(): Promise<void>;\n}\n\nexport async function bullmqAdmin(redisUrl: string, queueName = 'efc'): Promise<TaskAdmin> {\n let bullmq: typeof BullMQNS;\n try {\n bullmq = await import('bullmq');\n } catch {\n throw new Error('[EFC] bullmq is not installed. Run: npm install bullmq');\n }\n const queue = new bullmq.Queue(queueName, { connection: parseRedisUrl(redisUrl) });\n\n const failedJobs = async (ids: string[]): Promise<BullMQNS.Job[]> => {\n if (ids.length === 0) return queue.getFailed(0, -1);\n const jobs = await Promise.all(ids.map((id) => queue.getJob(id)));\n return jobs.filter((j): j is BullMQNS.Job => j != null && j.failedReason != null);\n };\n\n return {\n async counts() {\n return queue.getJobCounts('waiting', 'active', 'delayed', 'completed', 'failed');\n },\n async listFailed({ limit, name }) {\n const jobs = await queue.getFailed(0, name ? -1 : limit - 1);\n return jobs\n .filter((j) => !name || j.name === name)\n .slice(0, limit)\n .map((j) => ({\n id: String(j.id),\n name: j.name,\n data: j.data,\n error: j.failedReason,\n attempts: j.attemptsMade,\n failedAt: j.finishedOn ? new Date(j.finishedOn) : undefined,\n }));\n },\n async retry(ids) {\n const jobs = await failedJobs(ids);\n for (const job of jobs) await job.retry('failed');\n return jobs.length;\n },\n async purge(ids) {\n const jobs = await failedJobs(ids);\n for (const job of jobs) await job.remove();\n return jobs.length;\n },\n async close() {\n await queue.close();\n },\n };\n}\n","import { Command } from 'commander';\nimport { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport pc from 'picocolors';\nimport { readEnvFile } from '../env.js';\n\nfunction findBin(name: string): string | undefined {\n let dir = process.cwd();\n for (;;) {\n const candidate = path.join(dir, 'node_modules', '.bin', name);\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n/**\n * Where migrations/seeds load from: src/ under tsx when it's installed (development),\n * otherwise the compiled dist/src (production images ship without devDependencies),\n * or src/ under plain node for JavaScript projects.\n */\nfunction resolveRuntime(useDist: boolean): { exec: string; root: string } {\n const cwd = process.cwd();\n const src = path.join(cwd, 'src');\n const dist = path.join(cwd, 'dist', 'src');\n const tsx = findBin('tsx');\n if (!useDist && tsx && fs.existsSync(src)) return { exec: tsx, root: src };\n if (fs.existsSync(dist)) return { exec: process.execPath, root: dist };\n return { exec: process.execPath, root: src };\n}\n\nfunction run(\n command: string,\n opts: Record<string, unknown> & { dist?: boolean; databaseUrl?: string },\n): void {\n const { exec, root } = resolveRuntime(Boolean(opts.dist));\n const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), 'db-runner.js');\n const payload = JSON.stringify({ ...opts, root });\n // .env fills gaps; real environment variables win, as with `efc start dev`.\n const env = { ...readEnvFile(), ...process.env };\n const child = spawn(exec, [runner, command, payload], { stdio: 'inherit', env });\n for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => child.kill(signal));\n child.on('exit', (code, signal) => process.exit(code ?? (signal ? 1 : 0)));\n}\n\nconst common = (cmd: Command) =>\n cmd\n .option('--database-url <url>', 'override DATABASE_URL')\n .option('--dist', 'load compiled files from dist/src even when tsx is installed');\n\nexport function dbCommand(): Command {\n const cmd = new Command('db').description('Database migrations, seeds and studio');\n\n common(cmd.command('migrate').description('Run pending migrations in src/migrations')).action(\n (opts: { databaseUrl?: string; dist?: boolean }) => run('migrate', opts),\n );\n\n common(cmd.command('rollback').description('Revert the last batch of migrations'))\n .option('--steps <n>', 'number of batches to revert', '1')\n .action((opts: { steps: string; databaseUrl?: string; dist?: boolean }) => {\n const steps = Number(opts.steps);\n if (!Number.isInteger(steps) || steps < 1) {\n console.error(pc.red('--steps must be a positive integer'));\n process.exit(1);\n }\n run('rollback', { ...opts, steps });\n });\n\n common(\n cmd\n .command('sync')\n .description('Bring tables/collections and indexes in line with the models in src/model(s)'),\n )\n .option('--dry-run', 'print the changes (SQL on PostgreSQL) without applying them')\n .action((opts: { databaseUrl?: string; dist?: boolean; dryRun?: boolean }) =>\n run('sync', opts),\n );\n\n common(cmd.command('status').description('List applied and pending migrations')).action(\n (opts: { databaseUrl?: string; dist?: boolean }) => run('status', opts),\n );\n\n common(\n cmd\n .command('seed')\n .description('Run seed scripts in src/seeds')\n .argument('[name]', 'run only this seed'),\n ).action((name: string | undefined, opts: { databaseUrl?: string; dist?: boolean }) =>\n run('seed', { ...opts, ...(name !== undefined && { seed: name }) }),\n );\n\n common(cmd.command('studio').description('Open a local, read-only database browser'))\n .option('-p, --port <port>', 'port to listen on (127.0.0.1 only)', '4983')\n .action((opts: { port: string; databaseUrl?: string; dist?: boolean }) =>\n run('studio', { ...opts, port: Number(opts.port) }),\n );\n\n return cmd;\n}\n"],"mappings":";;;;;;;;;;;;AACA,OAAOA,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,SAAAC,cAAa;AACtB,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,gBAAe;;;ACLxB,SAAS,eAAe;AACxB,SAAS,aAAgC;AACzC,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,OAAO,QAAQ;AAER,SAAS,eAAwB;AACtC,QAAM,MAAM,IAAI,QAAQ,OAAO;AAE/B,MACG,SAAS,UAAU,YAAY,EAC/B,YAAY,sBAAsB,EAClC,OAAO,CAAC,SAAiB;AACxB,QAAI,SAAS,OAAO;AAClB,eAAS;AAAA,IACX,WAAW,SAAS,QAAQ;AAC1B,gBAAU;AAAA,IACZ,OAAO;AACL,cAAQ,MAAM,GAAG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;AACL,EAAAC,KAAI;AACN;AAEA,SAASA,OAAY;AACnB,QAAM,UAAU,IAAIC,SAAQ,KAAK,EAAE,YAAY,0BAA0B,EAAE,QAAQ,OAAO;AAE1F,UAAQ,WAAW,aAAa,CAAC;AACjC,UAAQ,WAAW,aAAa,CAAC;AACjC,UAAQ,WAAW,WAAW,CAAC;AAC/B,UAAQ,WAAW,gBAAgB,CAAC;AACpC,UAAQ,WAAW,UAAU,CAAC;AAE9B,aAAW,OAAO,oBAAoB,GAAG;AACvC,YAAQ,WAAW,GAAG;AAAA,EACxB;AAEA,UAAQ,MAAM,QAAQ,IAAI;AAC5B;","names":["fs","path","spawn","fileURLToPath","Command","Command","spawn","path","fs","pc","Command","spawn","pc","Command","fs","path","pc","Command","path","fs","pc","fs","path","Command","pc","ids","pc","Command","Command","pc","path","fs","Command","spawn","fs","path","pc","findBin","path","fs","run","spawn","Command","pc","fs","fileURLToPath","path","spawn","run","Command"]}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
# Auth — API Reference
|
|
2
|
+
|
|
3
|
+
EFC ships a JWT-based authentication module with two delivery strategies. All functions are exported from `express-file-cluster/auth`.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import {
|
|
7
|
+
issueToken,
|
|
8
|
+
revokeToken,
|
|
9
|
+
revokeSession,
|
|
10
|
+
revokeAllSessions,
|
|
11
|
+
signToken,
|
|
12
|
+
requireAuth,
|
|
13
|
+
getCurrentUser,
|
|
14
|
+
} from 'express-file-cluster/auth';
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Auth must be configured before any of these functions are called. Configuration happens automatically inside `ignite()` when `jwtSecret` is provided.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## `issueToken(res, payload)`
|
|
22
|
+
|
|
23
|
+
Signs a JWT and sets it as an `HttpOnly` cookie on the response. Use with the `'http-only'` auth strategy.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
async function issueToken(
|
|
27
|
+
res: Response,
|
|
28
|
+
payload: Record<string, unknown>,
|
|
29
|
+
): Promise<void>
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
| Parameter | Type | Description |
|
|
33
|
+
|---|---|---|
|
|
34
|
+
| `res` | `Response` | Express response object |
|
|
35
|
+
| `payload` | `Record<string, unknown>` | JWT claims (e.g. `{ sub: user.id, role: user.role }`) |
|
|
36
|
+
|
|
37
|
+
The cookie is named `efc_token` and is set with:
|
|
38
|
+
|
|
39
|
+
- `HttpOnly: true` — not accessible via `document.cookie`
|
|
40
|
+
- `Secure: true` — only sent over HTTPS (when `NODE_ENV === 'production'`)
|
|
41
|
+
- `SameSite: Strict` — only sent on same-site requests
|
|
42
|
+
- `Domain: COOKIE_DOMAIN` — set when the `COOKIE_DOMAIN` env var is configured
|
|
43
|
+
|
|
44
|
+
**Example:**
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
// src/api/auth/login.ts
|
|
48
|
+
import { issueToken } from 'express-file-cluster/auth';
|
|
49
|
+
|
|
50
|
+
export const POST = async (req, res) => {
|
|
51
|
+
const user = await verifyCredentials(req.body.email, req.body.password);
|
|
52
|
+
await issueToken(res, { sub: user.id, role: user.role });
|
|
53
|
+
res.json({ message: 'Logged in' });
|
|
54
|
+
};
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## `revokeToken(res)`
|
|
60
|
+
|
|
61
|
+
Clears the `efc_token` cookie. Use with the `'http-only'` strategy.
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
function revokeToken(res: Response): void
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
**Example:**
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
// src/api/auth/logout.ts
|
|
71
|
+
import { revokeToken } from 'express-file-cluster/auth';
|
|
72
|
+
|
|
73
|
+
export const POST = async (req, res) => {
|
|
74
|
+
revokeToken(res);
|
|
75
|
+
res.json({ message: 'Logged out' });
|
|
76
|
+
};
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
This only removes the cookie — a copy of the token stays valid until it expires. To actually invalidate it, configure a `cache` and use `revokeSession`.
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## `revokeSession(req, res?)`
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
async function revokeSession(req: Request, res?: Response): Promise<void>
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Rejects the token the request was authenticated with — `requireAuth` answers 401 for it from now until it would have expired. Passing `res` also clears the cookie (http-only strategy). Requires `cache` in `ignite()`; throws if the cache is unreachable.
|
|
90
|
+
|
|
91
|
+
## `revokeAllSessions(userId)`
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
async function revokeAllSessions(userId: string | number): Promise<void>
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Rejects every token issued to that user (`sub` or `id` claim) before now — "log out everywhere" or after a password change. Tokens issued afterwards are unaffected. Requires `cache`.
|
|
98
|
+
|
|
99
|
+
Every token EFC signs carries a `jti` and an issue time, which these checks use. See [Caching & Sessions](../guides/caching.md#session-revocation) for the outage behaviour.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## `signToken(payload)`
|
|
104
|
+
|
|
105
|
+
Signs a JWT and returns the token string. Use with the `'localStorage'` strategy; the client stores the token and attaches it as `Authorization: Bearer <token>`.
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
async function signToken(
|
|
109
|
+
payload: Record<string, unknown>,
|
|
110
|
+
): Promise<string>
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
**Example:**
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
// src/api/auth/login.ts
|
|
117
|
+
import { signToken } from 'express-file-cluster/auth';
|
|
118
|
+
|
|
119
|
+
export const POST = async (req, res) => {
|
|
120
|
+
const user = await verifyCredentials(req.body.email, req.body.password);
|
|
121
|
+
const token = await signToken({ sub: user.id, role: user.role });
|
|
122
|
+
res.json({ token });
|
|
123
|
+
};
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
The client then stores the token (e.g. `localStorage.setItem('token', token)`) and sends it on subsequent requests:
|
|
127
|
+
|
|
128
|
+
```http
|
|
129
|
+
Authorization: Bearer <token>
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## `requireAuth`
|
|
135
|
+
|
|
136
|
+
Express middleware that verifies the JWT and attaches the decoded payload to `req.user`. Returns `401 Unauthorized` if the token is missing, expired, or invalid.
|
|
137
|
+
|
|
138
|
+
Used bare, it only checks that the token is valid. Called with one or more role names, it returns a middleware that *also* enforces `payload.role` is one of them — returning `403 Forbidden` otherwise.
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
interface RequireAuth {
|
|
142
|
+
(req: Request, res: Response, next: NextFunction): void; // bare — auth only
|
|
143
|
+
(...roles: string[]): RequestHandler; // requireAuth('admin') — auth + role check
|
|
144
|
+
}
|
|
145
|
+
const requireAuth: RequireAuth
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Behaviour depends on the configured `authStrategy`:
|
|
149
|
+
|
|
150
|
+
| Strategy | Token source |
|
|
151
|
+
|---|---|
|
|
152
|
+
| `'http-only'` | `req.cookies.efc_token` |
|
|
153
|
+
| `'localStorage'` | `Authorization: Bearer <token>` header |
|
|
154
|
+
|
|
155
|
+
**Route-level, auth only (protects all handlers in the file):**
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
// src/api/users/index.ts
|
|
159
|
+
import { requireAuth } from 'express-file-cluster/auth';
|
|
160
|
+
|
|
161
|
+
export const middlewares = [requireAuth];
|
|
162
|
+
|
|
163
|
+
export const GET = async (req, res) => {
|
|
164
|
+
// req.user is populated here
|
|
165
|
+
res.json({ userId: (req as any).user.sub });
|
|
166
|
+
};
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
**Route-level, auth + role:**
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
// src/api/admin/users.ts
|
|
173
|
+
import { requireAuth } from 'express-file-cluster/auth';
|
|
174
|
+
|
|
175
|
+
export const middlewares = [requireAuth('admin')];
|
|
176
|
+
|
|
177
|
+
export const GET = async (req, res) => {
|
|
178
|
+
// only reachable when payload.role === 'admin'
|
|
179
|
+
res.json({ users: [] });
|
|
180
|
+
};
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Pass multiple roles to allow any of them: `requireAuth('user', 'admin')`.
|
|
184
|
+
|
|
185
|
+
**Handler-level (protects one method):**
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { compose } from 'express-file-cluster';
|
|
189
|
+
import { requireAuth } from 'express-file-cluster/auth';
|
|
190
|
+
|
|
191
|
+
export const DELETE = compose(requireAuth('admin'), async (req, res) => {
|
|
192
|
+
// only DELETE requires auth + the admin role
|
|
193
|
+
res.status(204).send();
|
|
194
|
+
});
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
---
|
|
198
|
+
|
|
199
|
+
## `getCurrentUser()`
|
|
200
|
+
|
|
201
|
+
Reads the JWT payload `requireAuth` attached to the in-flight request, from anywhere in the async call chain — not just where `req` is in scope. Backed by `AsyncLocalStorage`; every request run through `ignite()` gets its own isolated context.
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
function getCurrentUser(): Record<string, unknown> | undefined
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Returns `undefined` outside a request, or on a request that never ran through `requireAuth` (e.g. a public route).
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
import { getCurrentUser } from 'express-file-cluster/auth';
|
|
211
|
+
|
|
212
|
+
export const GET = async (req, res) => {
|
|
213
|
+
const user = getCurrentUser(); // same payload as req.user here, but callable from deeper code paths
|
|
214
|
+
res.json({ userId: user?.['sub'] });
|
|
215
|
+
};
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
This is also what powers the `'$currentUser'` / `'$currentUser.<key>'` `defineModel` default operator codes — see the [`db` API reference](./db.md#default-value-operator-codes) — so a `createdBy` field can be populated automatically on `.create()` without threading `req.user` through every route handler.
|
|
219
|
+
|
|
220
|
+
---
|
|
221
|
+
|
|
222
|
+
## Token lifetime
|
|
223
|
+
|
|
224
|
+
Controlled by the `JWT_EXPIRES_IN` environment variable. Default: `7d`.
|
|
225
|
+
|
|
226
|
+
Accepts any value the [`jose`](https://github.com/panva/jose) library supports: `15m`, `1h`, `7d`, `30d`, etc.
|
|
227
|
+
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
## Algorithm
|
|
231
|
+
|
|
232
|
+
Tokens are signed with **HS256** (HMAC-SHA256). The secret is UTF-8 encoded before signing. Asymmetric algorithms (RS256, ES256) are not currently supported.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# `compose(...handlers)` — API Reference
|
|
2
|
+
|
|
3
|
+
`compose` chains multiple Express `RequestHandler` functions into a single handler. It is the primary tool for handler-level (single-method) middleware.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { compose } from 'express-file-cluster';
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Signature
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
function compose(...handlers: RequestHandler[]): RequestHandler
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
**Parameters:** one or more Express `RequestHandler` functions.
|
|
18
|
+
|
|
19
|
+
**Returns:** a single `RequestHandler` that runs the provided handlers in sequence.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { compose } from 'express-file-cluster';
|
|
27
|
+
import { validateBody } from '../../middlewares/validation';
|
|
28
|
+
import { CreateUserSchema } from '../../schemas/user';
|
|
29
|
+
|
|
30
|
+
export const POST = compose(
|
|
31
|
+
validateBody(CreateUserSchema),
|
|
32
|
+
async (req, res) => {
|
|
33
|
+
// validateBody ran first — req.body is validated
|
|
34
|
+
res.status(201).json({ id: 'new-id' });
|
|
35
|
+
},
|
|
36
|
+
);
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Behaviour
|
|
42
|
+
|
|
43
|
+
- Handlers are called in the order they are passed.
|
|
44
|
+
- Each handler receives the real `next` function of its predecessor; calling `next()` advances to the next handler in the chain.
|
|
45
|
+
- If the last handler calls `next()`, control passes to the surrounding Express middleware chain (equivalent to the route calling `next()`).
|
|
46
|
+
- If any handler throws synchronously or returns a rejected promise, the error is forwarded to `next(err)` and bubbles up to the global error handler.
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Composing async middleware
|
|
51
|
+
|
|
52
|
+
`compose` works seamlessly with async functions:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
export const DELETE = compose(
|
|
56
|
+
requireAuth,
|
|
57
|
+
async (req, res, next) => {
|
|
58
|
+
const resource = await db.findById(req.params.id);
|
|
59
|
+
if (!resource) return next(new HttpError(404, 'Not found'));
|
|
60
|
+
(req as any).resource = resource;
|
|
61
|
+
next();
|
|
62
|
+
},
|
|
63
|
+
async (req, res) => {
|
|
64
|
+
await (req as any).resource.delete();
|
|
65
|
+
res.status(204).send();
|
|
66
|
+
},
|
|
67
|
+
);
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## When to use `compose` vs. `middlewares`
|
|
73
|
+
|
|
74
|
+
| Scenario | Recommended approach |
|
|
75
|
+
|---|---|
|
|
76
|
+
| Guard applies to every handler in the file | `export const middlewares = [guard]` |
|
|
77
|
+
| Guard applies to one specific method | `export const POST = compose(guard, handler)` |
|
|
78
|
+
| Chaining multiple guards on one method | `export const POST = compose(guard1, guard2, handler)` |
|