express-file-cluster 0.3.14 → 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.
Files changed (116) hide show
  1. package/README.md +204 -52
  2. package/dist/auth/index.cjs +12 -2
  3. package/dist/auth/index.cjs.map +1 -1
  4. package/dist/auth/index.d.cts +13 -2
  5. package/dist/auth/index.d.ts +13 -2
  6. package/dist/auth/index.js +12 -2
  7. package/dist/chunk-3VWD2ZED.js +60 -0
  8. package/dist/chunk-3VWD2ZED.js.map +1 -0
  9. package/dist/chunk-47K2532L.cjs +196 -0
  10. package/dist/chunk-47K2532L.cjs.map +1 -0
  11. package/dist/chunk-5PDAWMGF.js +438 -0
  12. package/dist/chunk-5PDAWMGF.js.map +1 -0
  13. package/dist/chunk-7YEX4MQV.cjs +38 -0
  14. package/dist/chunk-7YEX4MQV.cjs.map +1 -0
  15. package/dist/chunk-ALBDM5R3.cjs +60 -0
  16. package/dist/chunk-ALBDM5R3.cjs.map +1 -0
  17. package/dist/chunk-JJJJTACK.js +196 -0
  18. package/dist/chunk-JJJJTACK.js.map +1 -0
  19. package/dist/chunk-LJNSJFOL.js +38 -0
  20. package/dist/chunk-LJNSJFOL.js.map +1 -0
  21. package/dist/chunk-M7MUPWCE.js +116 -0
  22. package/dist/chunk-M7MUPWCE.js.map +1 -0
  23. package/dist/chunk-PMF4GMHD.js +154 -0
  24. package/dist/chunk-PMF4GMHD.js.map +1 -0
  25. package/dist/chunk-QTRGJ2EN.cjs +2635 -0
  26. package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
  27. package/dist/chunk-RSBW2B3D.cjs +126 -0
  28. package/dist/chunk-RSBW2B3D.cjs.map +1 -0
  29. package/dist/chunk-RTFJ32T5.js +2635 -0
  30. package/dist/chunk-RTFJ32T5.js.map +1 -0
  31. package/dist/chunk-SFVEQ2T5.cjs +438 -0
  32. package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
  33. package/dist/chunk-SZT36SGB.cjs +154 -0
  34. package/dist/chunk-SZT36SGB.cjs.map +1 -0
  35. package/dist/chunk-TI24L4XE.cjs.map +1 -1
  36. package/dist/chunk-ULQXD4YZ.cjs +116 -0
  37. package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
  38. package/dist/chunk-VYHJX54R.js +126 -0
  39. package/dist/chunk-VYHJX54R.js.map +1 -0
  40. package/dist/cli/db-runner.cjs +497 -0
  41. package/dist/cli/db-runner.cjs.map +1 -0
  42. package/dist/cli/db-runner.d.cts +2 -0
  43. package/dist/cli/db-runner.d.ts +2 -0
  44. package/dist/cli/db-runner.js +497 -0
  45. package/dist/cli/db-runner.js.map +1 -0
  46. package/dist/cli/index.cjs +447 -69
  47. package/dist/cli/index.cjs.map +1 -1
  48. package/dist/cli/index.js +473 -95
  49. package/dist/cli/index.js.map +1 -1
  50. package/dist/docs/api-reference/auth.md +232 -0
  51. package/dist/docs/api-reference/compose.md +78 -0
  52. package/dist/docs/api-reference/db.md +351 -0
  53. package/dist/docs/api-reference/http-error.md +109 -0
  54. package/dist/docs/api-reference/ignite.md +323 -0
  55. package/dist/docs/api-reference/table.md +250 -0
  56. package/dist/docs/api-reference/tasks.md +140 -0
  57. package/dist/docs/cli/db.md +38 -0
  58. package/dist/docs/cli/diagnostics.md +145 -0
  59. package/dist/docs/cli/generate.md +120 -0
  60. package/dist/docs/cli/index.md +48 -0
  61. package/dist/docs/cli/start.md +112 -0
  62. package/dist/docs/contributing/index.md +139 -0
  63. package/dist/docs/core-concepts/background-tasks.md +228 -0
  64. package/dist/docs/core-concepts/clustering.md +114 -0
  65. package/dist/docs/core-concepts/file-based-routing.md +235 -0
  66. package/dist/docs/core-concepts/index.md +79 -0
  67. package/dist/docs/core-concepts/middleware.md +144 -0
  68. package/dist/docs/getting-started/index.md +91 -0
  69. package/dist/docs/getting-started/project-structure.md +154 -0
  70. package/dist/docs/guides/ai-agents.md +48 -0
  71. package/dist/docs/guides/authentication.md +196 -0
  72. package/dist/docs/guides/caching.md +124 -0
  73. package/dist/docs/guides/database.md +217 -0
  74. package/dist/docs/guides/deployment.md +171 -0
  75. package/dist/docs/guides/environment-variables.md +106 -0
  76. package/dist/docs/guides/error-handling.md +172 -0
  77. package/dist/docs/guides/generated-portals.md +115 -0
  78. package/dist/docs/guides/logging.md +70 -0
  79. package/dist/docs/guides/mailer.md +166 -0
  80. package/dist/docs/guides/migrations.md +106 -0
  81. package/dist/docs/guides/rbac.md +89 -0
  82. package/dist/docs/guides/validation.md +95 -0
  83. package/dist/docs/index.md +93 -0
  84. package/dist/docs/skills/SKILL.md +44 -0
  85. package/dist/docs/skills/api-surface.md +308 -0
  86. package/dist/docs/skills/auth-internals.md +141 -0
  87. package/dist/docs/skills/pre-flight.md +142 -0
  88. package/dist/docs/skills/routing-rules.md +114 -0
  89. package/dist/docs/skills/tasks-internals.md +172 -0
  90. package/dist/docs/skills/what-not-to-invent.md +251 -0
  91. package/dist/index.cjs +289 -391
  92. package/dist/index.cjs.map +1 -1
  93. package/dist/index.d.cts +472 -7
  94. package/dist/index.d.ts +472 -7
  95. package/dist/index.js +283 -385
  96. package/dist/index.js.map +1 -1
  97. package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
  98. package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
  99. package/dist/pgboss-backend-UUJOVEYK.js +14 -0
  100. package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
  101. package/dist/tasks/index.cjs.map +1 -1
  102. package/dist/tasks/index.d.cts +1 -1
  103. package/dist/tasks/index.d.ts +1 -1
  104. package/dist/types-DJCPAsM4.d.cts +541 -0
  105. package/dist/types-DJCPAsM4.d.ts +541 -0
  106. package/package.json +28 -5
  107. package/dist/chunk-6522HS2J.cjs +0 -99
  108. package/dist/chunk-6522HS2J.cjs.map +0 -1
  109. package/dist/chunk-DGVOJNR6.cjs +0 -55
  110. package/dist/chunk-DGVOJNR6.cjs.map +0 -1
  111. package/dist/chunk-KOHLLUN7.js +0 -55
  112. package/dist/chunk-KOHLLUN7.js.map +0 -1
  113. package/dist/chunk-VIP3PFWZ.js +0 -99
  114. package/dist/chunk-VIP3PFWZ.js.map +0 -1
  115. package/dist/types-BusbSenn.d.cts +0 -162
  116. package/dist/types-BusbSenn.d.ts +0 -162
@@ -1,16 +1,26 @@
1
1
  #!/usr/bin/env node
2
- "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
+ "use strict"; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
3
3
 
4
- var _chunkDGVOJNR6cjs = require('../chunk-DGVOJNR6.cjs');
4
+ var _chunkULQXD4YZcjs = require('../chunk-ULQXD4YZ.cjs');
5
+
6
+
7
+ var _chunkSZT36SGBcjs = require('../chunk-SZT36SGB.cjs');
8
+ require('../chunk-7YEX4MQV.cjs');
9
+ require('../chunk-TI24L4XE.cjs');
10
+ require('../chunk-RSBW2B3D.cjs');
5
11
 
6
12
  // src/cli/index.ts
13
+ var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
14
+ var _path = require('path'); var _path2 = _interopRequireDefault(_path);
15
+ var _child_process = require('child_process');
16
+ var _url = require('url');
7
17
  var _commander = require('commander');
8
18
 
9
19
  // src/cli/commands/start.ts
10
20
 
11
- var _child_process = require('child_process');
12
- var _path = require('path'); var _path2 = _interopRequireDefault(_path);
13
- var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
21
+
22
+
23
+
14
24
  var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
15
25
  function startCommand() {
16
26
  const cmd = new (0, _commander.Command)("start");
@@ -69,7 +79,11 @@ function startDev() {
69
79
  }
70
80
  console.log(_picocolors2.default.cyan("[EFC] Starting development server\u2026"));
71
81
  console.log(_picocolors2.default.dim(` Entry: ${entry}`));
72
- console.log(_picocolors2.default.dim(" .env is re-read fresh on every restart (no need to stop/restart `efc start dev` for .env changes to take effect)"));
82
+ console.log(
83
+ _picocolors2.default.dim(
84
+ " .env is re-read fresh on every restart (no need to stop/restart `efc start dev` for .env changes to take effect)"
85
+ )
86
+ );
73
87
  const cwd = process.cwd();
74
88
  function findTsx() {
75
89
  let dir = cwd;
@@ -77,11 +91,18 @@ function startDev() {
77
91
  const candidate = _path2.default.join(dir, "node_modules", ".bin", "tsx");
78
92
  if (_fs2.default.existsSync(candidate)) return candidate;
79
93
  const parent = _path2.default.dirname(dir);
80
- if (parent === dir) return "tsx";
94
+ if (parent === dir) return void 0;
81
95
  dir = parent;
82
96
  }
83
97
  }
84
98
  const tsx = findTsx();
99
+ const isJs = /\.(m?js|cjs)$/.test(entry);
100
+ if (!tsx && !isJs) {
101
+ console.error(
102
+ _picocolors2.default.red("[EFC] tsx is required to run TypeScript in development. Run: npm install -D tsx")
103
+ );
104
+ process.exit(1);
105
+ }
85
106
  const preloadPath = writeDevEnvPreload(cwd);
86
107
  const env = {
87
108
  ...process.env,
@@ -92,14 +113,26 @@ function startDev() {
92
113
  NODE_ENV: "development",
93
114
  NODE_OPTIONS: [process.env["NODE_OPTIONS"], `--import ${preloadPath}`].filter(Boolean).join(" ")
94
115
  };
95
- const child = _child_process.spawn.call(void 0, tsx, ["watch", "--include", "src", entry], { stdio: "inherit", env });
96
- child.on("exit", (code) => process.exit(_nullishCoalesce(code, () => ( 0))));
116
+ const child = tsx ? _child_process.spawn.call(void 0, tsx, ["watch", "--include", "src", entry], { stdio: "inherit", env }) : _child_process.spawn.call(void 0, process.execPath, ["--watch", "--watch-path", _path2.default.join(cwd, "src"), entry], {
117
+ stdio: "inherit",
118
+ env
119
+ });
120
+ forwardSignals(child);
121
+ }
122
+ function forwardSignals(child) {
123
+ for (const signal of ["SIGTERM", "SIGINT"]) {
124
+ process.on(signal, () => child.kill(signal));
125
+ }
126
+ child.on("exit", (code, signal) => process.exit(_nullishCoalesce(code, () => ( (signal ? 1 : 0)))));
97
127
  }
98
128
  function startProd() {
99
129
  const cwd = process.cwd();
100
- const distEntry = _path2.default.join(cwd, "dist", "index.js");
101
- if (!_fs2.default.existsSync(distEntry)) {
102
- console.error(_picocolors2.default.red("[EFC] dist/index.js not found. Run `efc build prod` first."));
130
+ const distEntry = [
131
+ _path2.default.join(cwd, "dist", "src", "index.js"),
132
+ _path2.default.join(cwd, "dist", "index.js")
133
+ ].find((f) => _fs2.default.existsSync(f));
134
+ if (!distEntry) {
135
+ console.error(_picocolors2.default.red("[EFC] dist/src/index.js not found. Run `efc build prod` first."));
103
136
  process.exit(1);
104
137
  }
105
138
  console.log(_picocolors2.default.cyan("[EFC] Starting production server\u2026"));
@@ -107,7 +140,7 @@ function startProd() {
107
140
  stdio: "inherit",
108
141
  env: { ...process.env, NODE_ENV: "production" }
109
142
  });
110
- child.on("exit", (code) => process.exit(_nullishCoalesce(code, () => ( 0))));
143
+ forwardSignals(child);
111
144
  }
112
145
  function resolveEntry() {
113
146
  const cwd = process.cwd();
@@ -147,15 +180,35 @@ function findBin(name) {
147
180
  dir = parent;
148
181
  }
149
182
  }
150
- function resolveEntry2() {
151
- const cwd = process.cwd();
152
- const candidates = [
153
- _path2.default.join(cwd, "src", "index.ts"),
154
- _path2.default.join(cwd, "index.ts"),
155
- _path2.default.join(cwd, "src", "index.js"),
156
- _path2.default.join(cwd, "index.js")
183
+ function writeAppTsupConfig(cwd) {
184
+ const pkgPath = _path2.default.join(cwd, "package.json");
185
+ const isEsm = _fs2.default.existsSync(pkgPath) && JSON.parse(_fs2.default.readFileSync(pkgPath, "utf8")).type === "module";
186
+ const entry = [
187
+ "src/**/*.{ts,mts,js,mjs}",
188
+ ...["efc.config.ts", "efc.config.js"].filter((f) => _fs2.default.existsSync(_path2.default.join(cwd, f))),
189
+ "!src/**/*.d.ts",
190
+ "!src/**/*.test.*",
191
+ "!src/**/__tests__/**"
157
192
  ];
158
- return _nullishCoalesce(candidates.find((f) => _fs2.default.existsSync(f)), () => ( null));
193
+ const config = `export default {
194
+ entry: ${JSON.stringify(entry)},
195
+ outDir: 'dist',
196
+ format: ['${isEsm ? "esm" : "cjs"}'],
197
+ bundle: false,
198
+ splitting: false,
199
+ clean: true,
200
+ sourcemap: true,
201
+ platform: 'node',
202
+ target: 'node18',
203
+ esbuildOptions(options) {
204
+ options.outbase = '.';
205
+ },
206
+ };
207
+ `;
208
+ const configPath = _path2.default.join(cwd, "node_modules", ".cache", "efc", "tsup.config.mjs");
209
+ _fs2.default.mkdirSync(_path2.default.dirname(configPath), { recursive: true });
210
+ _fs2.default.writeFileSync(configPath, config);
211
+ return configPath;
159
212
  }
160
213
  function hasTsupConfig() {
161
214
  const cwd = process.cwd();
@@ -172,8 +225,8 @@ function buildProd() {
172
225
  console.log(_picocolors2.default.cyan("[EFC] Building for production\u2026"));
173
226
  const tsconfig = findTsConfig();
174
227
  if (!tsconfig) {
175
- console.error(_picocolors2.default.red("[EFC] No tsconfig.json found in the current directory."));
176
- process.exit(1);
228
+ transpile();
229
+ return;
177
230
  }
178
231
  const tsc = _child_process.spawn.call(void 0, findBin("tsc"), ["--noEmit", "--project", tsconfig], { stdio: "inherit" });
179
232
  tsc.on("exit", (code) => {
@@ -181,28 +234,46 @@ function buildProd() {
181
234
  console.error(_picocolors2.default.red("[EFC] TypeScript errors found. Fix them before building."));
182
235
  process.exit(1);
183
236
  }
184
- let tsupArgs;
185
- if (hasTsupConfig()) {
186
- tsupArgs = [];
237
+ transpile();
238
+ });
239
+ }
240
+ function copyJsProject(cwd) {
241
+ const dist = _path2.default.join(cwd, "dist");
242
+ _fs2.default.rmSync(dist, { recursive: true, force: true });
243
+ _fs2.default.cpSync(_path2.default.join(cwd, "src"), _path2.default.join(dist, "src"), {
244
+ recursive: true,
245
+ filter: (src) => !/(\.test\.[cm]?js$|[\\/]__tests__([\\/]|$))/.test(src)
246
+ });
247
+ for (const f of ["efc.config.js", "efc.config.mjs"]) {
248
+ if (_fs2.default.existsSync(_path2.default.join(cwd, f))) _fs2.default.copyFileSync(_path2.default.join(cwd, f), _path2.default.join(dist, f));
249
+ }
250
+ console.log(_picocolors2.default.green("[EFC] Build complete \u2192 dist/ (JavaScript copied as-is)"));
251
+ }
252
+ function transpile() {
253
+ let tsupArgs;
254
+ const cwd = process.cwd();
255
+ if (hasTsupConfig()) {
256
+ tsupArgs = [];
257
+ } else {
258
+ const hasTs = _fs2.default.existsSync(_path2.default.join(cwd, "src", "index.ts"));
259
+ if (!hasTs && !_fs2.default.existsSync(_path2.default.join(cwd, "src", "index.js"))) {
260
+ console.error(_picocolors2.default.red("[EFC] Could not find entry point. Expected src/index.ts"));
261
+ process.exit(1);
262
+ return;
263
+ }
264
+ if (!hasTs && !findTsConfig()) {
265
+ copyJsProject(cwd);
266
+ return;
267
+ }
268
+ tsupArgs = ["--config", writeAppTsupConfig(cwd)];
269
+ }
270
+ const tsup = _child_process.spawn.call(void 0, findBin("tsup"), tsupArgs, { stdio: "inherit" });
271
+ tsup.on("exit", (tsupCode) => {
272
+ if (tsupCode === 0) {
273
+ console.log(_picocolors2.default.green("[EFC] Build complete \u2192 dist/"));
187
274
  } else {
188
- const entry = resolveEntry2();
189
- if (!entry) {
190
- console.error(
191
- _picocolors2.default.red("[EFC] Could not find entry point. Expected src/index.ts or index.ts")
192
- );
193
- process.exit(1);
194
- return;
195
- }
196
- tsupArgs = [entry, "--format", "cjs,esm", "--clean", "--target", "node18"];
275
+ process.exit(_nullishCoalesce(tsupCode, () => ( 1)));
197
276
  }
198
- const tsup = _child_process.spawn.call(void 0, findBin("tsup"), tsupArgs, { stdio: "inherit" });
199
- tsup.on("exit", (tsupCode) => {
200
- if (tsupCode === 0) {
201
- console.log(_picocolors2.default.green("[EFC] Build complete \u2192 dist/"));
202
- } else {
203
- process.exit(_nullishCoalesce(tsupCode, () => ( 1)));
204
- }
205
- });
206
277
  });
207
278
  }
208
279
 
@@ -238,6 +309,8 @@ function generateCommand() {
238
309
  cmd.command("route <routePath>").description("Scaffold a route module, e.g. users/[id]").action((routePath) => generateRoute(routePath));
239
310
  cmd.command("task <name>").description("Scaffold a background task module").action((name) => generateTask(name));
240
311
  cmd.command("middleware <name>").description("Scaffold a middleware module").action((name) => generateMiddleware(name));
312
+ cmd.command("migration <name>").description("Scaffold a timestamped migration in src/migrations").action((name) => generateMigration(name));
313
+ cmd.command("seed <name>").description("Scaffold a seed script in src/seeds").action((name) => generateSeed(name));
241
314
  return cmd;
242
315
  }
243
316
  function writeFile(filePath, content) {
@@ -331,12 +404,230 @@ export function ${name}(req: Request, res: Response, next: NextFunction): void {
331
404
  writeFile(filePath, content);
332
405
  console.log(_picocolors2.default.cyan(`[EFC] Middleware scaffolded`));
333
406
  }
407
+ var isTypeScript = () => _fs2.default.existsSync(_path2.default.join(process.cwd(), "tsconfig.json"));
408
+ var snake = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_|_$/g, "").toLowerCase();
409
+ function generateMigration(name) {
410
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
411
+ const ts = isTypeScript();
412
+ const filePath = _path2.default.join(
413
+ process.cwd(),
414
+ "src",
415
+ "migrations",
416
+ `${stamp}_${snake(name)}.${ts ? "ts" : "js"}`
417
+ );
418
+ const typeImport = ts ? "import type { MigrationContext } from 'express-file-cluster';\n" : "";
419
+ const ctx = ts ? "{ db, engine }: MigrationContext" : "{ db, engine }";
420
+ const ret = ts ? ": Promise<void>" : "";
421
+ writeFile(
422
+ filePath,
423
+ `${typeImport}// import { User } from '../model/User.js';
424
+
425
+ // \`efc db migrate\` runs up(); \`efc db rollback\` runs down(). \`db\` is the native client:
426
+ // a mongoose Connection on MongoDB, a node-postgres Pool on PostgreSQL.
427
+ export async function up(${ctx})${ret} {
428
+ // await User.sync(); // create the table/collection, new columns and indexes
429
+ }
430
+
431
+ export async function down(${ctx})${ret} {
432
+ // if (engine === 'postgresql') await db.query('DROP TABLE IF EXISTS users');
433
+ }
434
+ `
435
+ );
436
+ console.log(_picocolors2.default.cyan("[EFC] Migration scaffolded \u2014 run `efc db migrate`"));
437
+ }
438
+ function generateSeed(name) {
439
+ const ts = isTypeScript();
440
+ const filePath = _path2.default.join(process.cwd(), "src", "seeds", `${snake(name)}.${ts ? "ts" : "js"}`);
441
+ const typeImport = ts ? "import type { MigrationContext } from 'express-file-cluster';\n" : "";
442
+ const ctx = ts ? "{ engine }: MigrationContext" : "{ engine }";
443
+ writeFile(
444
+ filePath,
445
+ `${typeImport}// import { User } from '../model/User.js';
446
+
447
+ // Run with \`efc db seed\` (all seeds) or \`efc db seed ${snake(name)}\`.
448
+ export default async function seed(${ctx}) {
449
+ // await User.createMany([{ name: 'Ada', email: 'ada@example.com' }]);
450
+ }
451
+ `
452
+ );
453
+ console.log(_picocolors2.default.cyan("[EFC] Seed scaffolded \u2014 run `efc db seed`"));
454
+ }
334
455
 
335
456
  // src/cli/commands/diagnostics.ts
336
457
 
337
458
 
338
459
 
339
460
 
461
+
462
+ // src/cli/env.ts
463
+
464
+
465
+ function readEnvFile(cwd = process.cwd()) {
466
+ const envPath = _path2.default.join(cwd, ".env");
467
+ if (!_fs2.default.existsSync(envPath)) return {};
468
+ const vars = {};
469
+ for (const line of _fs2.default.readFileSync(envPath, "utf8").split("\n")) {
470
+ const trimmed = line.trim();
471
+ if (!trimmed || trimmed.startsWith("#")) continue;
472
+ const eq = trimmed.indexOf("=");
473
+ if (eq === -1) continue;
474
+ const key = trimmed.slice(0, eq).trim();
475
+ const raw = trimmed.slice(eq + 1).trim();
476
+ vars[key] = raw.replace(/^(['"])(.*)\1$/, "$2");
477
+ }
478
+ return vars;
479
+ }
480
+ function envVar(key, cwd = process.cwd()) {
481
+ return process.env[key] || readEnvFile(cwd)[key] || void 0;
482
+ }
483
+
484
+ // src/cli/commands/task-admin.ts
485
+
486
+
487
+
488
+ // src/tasks/admin.ts
489
+ async function bullmqAdmin(redisUrl, queueName = "efc") {
490
+ let bullmq;
491
+ try {
492
+ bullmq = await Promise.resolve().then(() => _interopRequireWildcard(require("bullmq")));
493
+ } catch (e) {
494
+ throw new Error("[EFC] bullmq is not installed. Run: npm install bullmq");
495
+ }
496
+ const queue = new bullmq.Queue(queueName, { connection: _chunkSZT36SGBcjs.parseRedisUrl.call(void 0, redisUrl) });
497
+ const failedJobs = async (ids2) => {
498
+ if (ids2.length === 0) return queue.getFailed(0, -1);
499
+ const jobs = await Promise.all(ids2.map((id) => queue.getJob(id)));
500
+ return jobs.filter((j) => j != null && j.failedReason != null);
501
+ };
502
+ return {
503
+ async counts() {
504
+ return queue.getJobCounts("waiting", "active", "delayed", "completed", "failed");
505
+ },
506
+ async listFailed({ limit, name }) {
507
+ const jobs = await queue.getFailed(0, name ? -1 : limit - 1);
508
+ return jobs.filter((j) => !name || j.name === name).slice(0, limit).map((j) => ({
509
+ id: String(j.id),
510
+ name: j.name,
511
+ data: j.data,
512
+ error: j.failedReason,
513
+ attempts: j.attemptsMade,
514
+ failedAt: j.finishedOn ? new Date(j.finishedOn) : void 0
515
+ }));
516
+ },
517
+ async retry(ids2) {
518
+ const jobs = await failedJobs(ids2);
519
+ for (const job of jobs) await job.retry("failed");
520
+ return jobs.length;
521
+ },
522
+ async purge(ids2) {
523
+ const jobs = await failedJobs(ids2);
524
+ for (const job of jobs) await job.remove();
525
+ return jobs.length;
526
+ },
527
+ async close() {
528
+ await queue.close();
529
+ }
530
+ };
531
+ }
532
+
533
+ // src/cli/commands/task-admin.ts
534
+ function withConnectionOptions(cmd) {
535
+ return cmd.option(
536
+ "--backend <backend>",
537
+ "bullmq | pg-boss (default: inferred from REDIS_URL / DATABASE_URL)"
538
+ ).option("--queue <name>", "queue name (tasks.queue in ignite())", "efc").option("--redis-url <url>", "Redis URL for BullMQ (default: REDIS_URL)").option("--database-url <url>", "Postgres URL for pg-boss (default: DATABASE_URL)");
539
+ }
540
+ async function connect(opts) {
541
+ const redisUrl = _nullishCoalesce(opts.redisUrl, () => ( envVar("REDIS_URL")));
542
+ const databaseUrl = _nullishCoalesce(opts.databaseUrl, () => ( envVar("DATABASE_URL")));
543
+ const backend = _nullishCoalesce(opts.backend, () => ( (redisUrl ? "bullmq" : _optionalChain([databaseUrl, 'optionalAccess', _ => _.startsWith, 'call', _2 => _2("postgres")]) ? "pg-boss" : "bullmq")));
544
+ if (backend === "bullmq") return bullmqAdmin(_nullishCoalesce(redisUrl, () => ( "redis://localhost:6379")), opts.queue);
545
+ if (backend === "pg-boss") {
546
+ if (!databaseUrl) throw new Error("[EFC] pg-boss needs DATABASE_URL (or --database-url)");
547
+ const { pgBossAdmin } = await Promise.resolve().then(() => _interopRequireWildcard(require("../pgboss-backend-3E6ATY42.cjs")));
548
+ return pgBossAdmin(databaseUrl, opts.queue);
549
+ }
550
+ throw new Error(`[EFC] Unknown task backend: ${backend}`);
551
+ }
552
+ async function run(opts, fn) {
553
+ let admin;
554
+ try {
555
+ admin = await connect(opts);
556
+ await fn(admin);
557
+ } catch (err) {
558
+ console.error(_picocolors2.default.red(err instanceof Error ? err.message : String(err)));
559
+ process.exitCode = 1;
560
+ } finally {
561
+ await _optionalChain([admin, 'optionalAccess', _3 => _3.close, 'call', _4 => _4(), 'access', _5 => _5.catch, 'call', _6 => _6(() => {
562
+ })]);
563
+ }
564
+ }
565
+ function ids(list, all) {
566
+ if (all) return [];
567
+ if (list.length === 0) {
568
+ console.error(_picocolors2.default.red("Pass job ids, or --all"));
569
+ process.exitCode = 1;
570
+ return null;
571
+ }
572
+ return list;
573
+ }
574
+ function taskAdminCommands() {
575
+ const failed = withConnectionOptions(
576
+ new (0, _commander.Command)("failed").description("List jobs that exhausted their retries (dead-lettered)")
577
+ ).option("-n, --limit <n>", "max jobs to show", "20").option("--name <task>", "only this task").option("--json", "print JSON").action(
578
+ (opts) => run(opts, async (admin) => {
579
+ const jobs = await admin.listFailed({
580
+ limit: Number(opts.limit),
581
+ ...opts.name !== void 0 && { name: opts.name }
582
+ });
583
+ if (opts.json) {
584
+ console.log(JSON.stringify(jobs, null, 2));
585
+ return;
586
+ }
587
+ const counts = await admin.counts();
588
+ console.log(
589
+ _picocolors2.default.bold("\n Queue ") + _picocolors2.default.dim(
590
+ Object.entries(counts).map(([k, v]) => `${k}=${v}`).join(" ")
591
+ ) + "\n"
592
+ );
593
+ if (jobs.length === 0) {
594
+ console.log(_picocolors2.default.green(" No failed jobs.\n"));
595
+ return;
596
+ }
597
+ for (const job of jobs) {
598
+ console.log(
599
+ ` ${_picocolors2.default.red("\u2717")} ${_picocolors2.default.cyan(job.name)} ${_picocolors2.default.dim("#" + job.id)} ` + _picocolors2.default.dim(
600
+ `attempts=${job.attempts}${job.failedAt ? " " + job.failedAt.toISOString() : ""}`
601
+ )
602
+ );
603
+ console.log(` ${job.error}`);
604
+ console.log(_picocolors2.default.dim(` data: ${JSON.stringify(job.data)}`));
605
+ }
606
+ console.log();
607
+ })
608
+ );
609
+ const retry = withConnectionOptions(
610
+ new (0, _commander.Command)("retry").description("Re-queue failed jobs").argument("[ids...]", "job ids")
611
+ ).option("--all", "retry every failed job").action((list, opts) => {
612
+ const selected = ids(list, opts.all);
613
+ if (!selected) return;
614
+ return run(opts, async (admin) => {
615
+ console.log(_picocolors2.default.green(`Retried ${await admin.retry(selected)} job(s)`));
616
+ });
617
+ });
618
+ const purge = withConnectionOptions(
619
+ new (0, _commander.Command)("purge").description("Delete failed jobs").argument("[ids...]", "job ids")
620
+ ).option("--all", "delete every failed job").action((list, opts) => {
621
+ const selected = ids(list, opts.all);
622
+ if (!selected) return;
623
+ return run(opts, async (admin) => {
624
+ console.log(_picocolors2.default.green(`Removed ${await admin.purge(selected)} job(s)`));
625
+ });
626
+ });
627
+ return [failed, retry, purge];
628
+ }
629
+
630
+ // src/cli/commands/diagnostics.ts
340
631
  function diagnosticsCommands() {
341
632
  return [routesCommand(), tasksCommand(), doctorCommand()];
342
633
  }
@@ -347,7 +638,7 @@ function routesCommand() {
347
638
  console.error(_picocolors2.default.red("[EFC] Could not find apiDir (expected src/api)"));
348
639
  process.exit(1);
349
640
  }
350
- const routes = _chunkDGVOJNR6cjs.scanDir.call(void 0, apiDir);
641
+ const routes = _chunkULQXD4YZcjs.scanDir.call(void 0, apiDir);
351
642
  if (routes.length === 0) {
352
643
  console.log(_picocolors2.default.yellow("No routes found."));
353
644
  return;
@@ -365,7 +656,11 @@ function routesCommand() {
365
656
  });
366
657
  }
367
658
  function tasksCommand() {
368
- return new (0, _commander.Command)("tasks").description("List registered background tasks").action(() => {
659
+ const cmd = new (0, _commander.Command)("tasks").description(
660
+ "List background tasks, or inspect the dead-letter queue (failed | retry | purge)"
661
+ );
662
+ for (const sub of taskAdminCommands()) cmd.addCommand(sub);
663
+ return cmd.action(() => {
369
664
  const tasksDir = resolveTasksDir();
370
665
  if (!tasksDir || !_fs2.default.existsSync(tasksDir)) {
371
666
  console.log(_picocolors2.default.yellow("No tasks directory found."));
@@ -383,21 +678,6 @@ function tasksCommand() {
383
678
  console.log();
384
679
  });
385
680
  }
386
- function readEnvFile(cwd) {
387
- const envPath = _path2.default.join(cwd, ".env");
388
- if (!_fs2.default.existsSync(envPath)) return {};
389
- const vars = {};
390
- for (const line of _fs2.default.readFileSync(envPath, "utf8").split("\n")) {
391
- const trimmed = line.trim();
392
- if (!trimmed || trimmed.startsWith("#")) continue;
393
- const eq = trimmed.indexOf("=");
394
- if (eq === -1) continue;
395
- const key = trimmed.slice(0, eq).trim();
396
- const raw = trimmed.slice(eq + 1).trim();
397
- vars[key] = raw.replace(/^(['"])(.*)\1$/, "$2");
398
- }
399
- return vars;
400
- }
401
681
  function doctorCommand() {
402
682
  return new (0, _commander.Command)("doctor").description("Validate config, env vars, and project setup").action(() => {
403
683
  const cwd = process.cwd();
@@ -459,14 +739,112 @@ function resolveTasksDir() {
459
739
  return _nullishCoalesce(candidates.find((d) => _fs2.default.existsSync(d)), () => ( null));
460
740
  }
461
741
 
742
+ // src/cli/commands/db.ts
743
+
744
+
745
+
746
+
747
+
748
+
749
+ function findBin2(name) {
750
+ let dir = process.cwd();
751
+ for (; ; ) {
752
+ const candidate = _path2.default.join(dir, "node_modules", ".bin", name);
753
+ if (_fs2.default.existsSync(candidate)) return candidate;
754
+ const parent = _path2.default.dirname(dir);
755
+ if (parent === dir) return void 0;
756
+ dir = parent;
757
+ }
758
+ }
759
+ function resolveRuntime(useDist) {
760
+ const cwd = process.cwd();
761
+ const src = _path2.default.join(cwd, "src");
762
+ const dist = _path2.default.join(cwd, "dist", "src");
763
+ const tsx = findBin2("tsx");
764
+ if (!useDist && tsx && _fs2.default.existsSync(src)) return { exec: tsx, root: src };
765
+ if (_fs2.default.existsSync(dist)) return { exec: process.execPath, root: dist };
766
+ return { exec: process.execPath, root: src };
767
+ }
768
+ function run2(command, opts) {
769
+ const { exec, root } = resolveRuntime(Boolean(opts.dist));
770
+ const runner = _path2.default.join(_path2.default.dirname(_url.fileURLToPath.call(void 0, import.meta.url)), "db-runner.js");
771
+ const payload = JSON.stringify({ ...opts, root });
772
+ const env = { ...readEnvFile(), ...process.env };
773
+ const child = _child_process.spawn.call(void 0, exec, [runner, command, payload], { stdio: "inherit", env });
774
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => child.kill(signal));
775
+ child.on("exit", (code, signal) => process.exit(_nullishCoalesce(code, () => ( (signal ? 1 : 0)))));
776
+ }
777
+ var common = (cmd) => cmd.option("--database-url <url>", "override DATABASE_URL").option("--dist", "load compiled files from dist/src even when tsx is installed");
778
+ function dbCommand() {
779
+ const cmd = new (0, _commander.Command)("db").description("Database migrations, seeds and studio");
780
+ common(cmd.command("migrate").description("Run pending migrations in src/migrations")).action(
781
+ (opts) => run2("migrate", opts)
782
+ );
783
+ common(cmd.command("rollback").description("Revert the last batch of migrations")).option("--steps <n>", "number of batches to revert", "1").action((opts) => {
784
+ const steps = Number(opts.steps);
785
+ if (!Number.isInteger(steps) || steps < 1) {
786
+ console.error(_picocolors2.default.red("--steps must be a positive integer"));
787
+ process.exit(1);
788
+ }
789
+ run2("rollback", { ...opts, steps });
790
+ });
791
+ common(
792
+ cmd.command("sync").description("Bring tables/collections and indexes in line with the models in src/model(s)")
793
+ ).option("--dry-run", "print the changes (SQL on PostgreSQL) without applying them").action(
794
+ (opts) => run2("sync", opts)
795
+ );
796
+ common(cmd.command("status").description("List applied and pending migrations")).action(
797
+ (opts) => run2("status", opts)
798
+ );
799
+ common(
800
+ cmd.command("seed").description("Run seed scripts in src/seeds").argument("[name]", "run only this seed")
801
+ ).action(
802
+ (name, opts) => run2("seed", { ...opts, ...name !== void 0 && { seed: name } })
803
+ );
804
+ common(cmd.command("studio").description("Open a local, read-only database browser")).option("-p, --port <port>", "port to listen on (127.0.0.1 only)", "4983").action(
805
+ (opts) => run2("studio", { ...opts, port: Number(opts.port) })
806
+ );
807
+ return cmd;
808
+ }
809
+
462
810
  // src/cli/index.ts
463
- var program = new (0, _commander.Command)("efc").description("Express File Cluster CLI").version("0.1.0");
464
- program.addCommand(startCommand());
465
- program.addCommand(buildCommand());
466
- program.addCommand(runCommand());
467
- program.addCommand(generateCommand());
468
- for (const cmd of diagnosticsCommands()) {
469
- program.addCommand(cmd);
470
- }
471
- program.parse(process.argv);
811
+ var { version } = JSON.parse(
812
+ _fs2.default.readFileSync(new URL("../../package.json", import.meta.url), "utf8")
813
+ );
814
+ function localCli() {
815
+ if (process.env["EFC_CLI_DELEGATED"]) return void 0;
816
+ const self = _fs2.default.realpathSync(_url.fileURLToPath.call(void 0, new URL("../..", import.meta.url)));
817
+ for (let dir = process.cwd(); ; dir = _path2.default.dirname(dir)) {
818
+ const pkgDir = _path2.default.join(dir, "node_modules", "express-file-cluster");
819
+ if (_fs2.default.existsSync(_path2.default.join(pkgDir, "package.json"))) {
820
+ const real = _fs2.default.realpathSync(pkgDir);
821
+ const cli = _path2.default.join(real, "dist", "cli", "index.js");
822
+ return real !== self && _fs2.default.existsSync(cli) ? cli : void 0;
823
+ }
824
+ if (_path2.default.dirname(dir) === dir) return void 0;
825
+ }
826
+ }
827
+ var delegate = localCli();
828
+ if (delegate) {
829
+ const child = _child_process.spawn.call(void 0, process.execPath, [delegate, ...process.argv.slice(2)], {
830
+ stdio: "inherit",
831
+ env: { ...process.env, EFC_CLI_DELEGATED: "1" }
832
+ });
833
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => child.kill(signal));
834
+ child.on("exit", (code, signal) => process.exit(_nullishCoalesce(code, () => ( (signal ? 1 : 0)))));
835
+ } else {
836
+ run3();
837
+ }
838
+ function run3() {
839
+ const program = new (0, _commander.Command)("efc").description("Express File Cluster CLI").version(version);
840
+ program.addCommand(startCommand());
841
+ program.addCommand(buildCommand());
842
+ program.addCommand(runCommand());
843
+ program.addCommand(generateCommand());
844
+ program.addCommand(dbCommand());
845
+ for (const cmd of diagnosticsCommands()) {
846
+ program.addCommand(cmd);
847
+ }
848
+ program.parse(process.argv);
849
+ }
472
850
  //# sourceMappingURL=index.cjs.map