express-file-cluster 0.11.0 → 0.12.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 (133) hide show
  1. package/dist/auth/index.cjs +8 -7
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +1 -1
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/auth/index.js +7 -5
  6. package/dist/{chunk-JBOMTZT5.js → chunk-3JQWQF2M.js} +3 -3
  7. package/dist/{chunk-WHBSVYUY.cjs → chunk-4FQP6QX3.cjs} +3 -3
  8. package/dist/{chunk-WHBSVYUY.cjs.map → chunk-4FQP6QX3.cjs.map} +1 -1
  9. package/dist/chunk-546TNO2V.js +226 -0
  10. package/dist/chunk-546TNO2V.js.map +1 -0
  11. package/dist/{chunk-EJDZZ4KX.js → chunk-74R37C4I.js} +48 -21
  12. package/dist/chunk-74R37C4I.js.map +1 -0
  13. package/dist/{chunk-H2PVWCWC.cjs → chunk-A2QGDWCG.cjs} +15 -8
  14. package/dist/chunk-A2QGDWCG.cjs.map +1 -0
  15. package/dist/{chunk-O2E7H2XA.js → chunk-BCSJOPYH.js} +2 -2
  16. package/dist/{chunk-DGYPIIJE.cjs → chunk-BJR42CN3.cjs} +89 -62
  17. package/dist/chunk-BJR42CN3.cjs.map +1 -0
  18. package/dist/{chunk-OM2XJJWX.js → chunk-EBJELA7T.js} +30 -25
  19. package/dist/chunk-EBJELA7T.js.map +1 -0
  20. package/dist/{chunk-IEF6AEK3.cjs → chunk-H6MHRHUP.cjs} +104 -50
  21. package/dist/chunk-H6MHRHUP.cjs.map +1 -0
  22. package/dist/{chunk-6WTMRZS7.cjs → chunk-IG3V2IOK.cjs} +57 -30
  23. package/dist/chunk-IG3V2IOK.cjs.map +1 -0
  24. package/dist/chunk-JAPZYQVJ.cjs +143 -0
  25. package/dist/chunk-JAPZYQVJ.cjs.map +1 -0
  26. package/dist/{chunk-QSIP7YLW.cjs → chunk-JHCXIYJH.cjs} +25 -48
  27. package/dist/chunk-JHCXIYJH.cjs.map +1 -0
  28. package/dist/{chunk-GWMW6XY7.cjs → chunk-JVB5NLEM.cjs} +15 -13
  29. package/dist/chunk-JVB5NLEM.cjs.map +1 -0
  30. package/dist/{chunk-LECHRAU3.js → chunk-LIAGVWFQ.js} +83 -56
  31. package/dist/chunk-LIAGVWFQ.js.map +1 -0
  32. package/dist/chunk-PUM5ZDAH.js +140 -0
  33. package/dist/chunk-PUM5ZDAH.js.map +1 -0
  34. package/dist/{chunk-CGY7JU4Y.cjs → chunk-PUYBKDYD.cjs} +11 -2
  35. package/dist/chunk-PUYBKDYD.cjs.map +1 -0
  36. package/dist/{chunk-336IU55W.js → chunk-QLM3JEER.js} +5 -3
  37. package/dist/{chunk-336IU55W.js.map → chunk-QLM3JEER.js.map} +1 -1
  38. package/dist/{chunk-SOU3PBJC.cjs → chunk-SV4C4HWP.cjs} +89 -89
  39. package/dist/{chunk-SOU3PBJC.cjs.map → chunk-SV4C4HWP.cjs.map} +1 -1
  40. package/dist/{chunk-2IDRC7RK.js → chunk-UJ2ISRLP.js} +11 -34
  41. package/dist/chunk-UJ2ISRLP.js.map +1 -0
  42. package/dist/chunk-URKE3OXN.cjs +226 -0
  43. package/dist/chunk-URKE3OXN.cjs.map +1 -0
  44. package/dist/{chunk-DTMDJGRW.cjs → chunk-VLGN3XUM.cjs} +40 -35
  45. package/dist/chunk-VLGN3XUM.cjs.map +1 -0
  46. package/dist/{chunk-R6GPQZLI.js → chunk-X2B7WBKH.js} +88 -34
  47. package/dist/chunk-X2B7WBKH.js.map +1 -0
  48. package/dist/chunk-Y7I2633P.js +12 -0
  49. package/dist/chunk-Y7I2633P.js.map +1 -0
  50. package/dist/{chunk-B6MB6HEG.js → chunk-ZBQUYFI3.js} +14 -7
  51. package/dist/chunk-ZBQUYFI3.js.map +1 -0
  52. package/dist/cli/db-runner.cjs +26 -25
  53. package/dist/cli/db-runner.cjs.map +1 -1
  54. package/dist/cli/db-runner.js +5 -3
  55. package/dist/cli/db-runner.js.map +1 -1
  56. package/dist/cli/index.cjs +16 -15
  57. package/dist/cli/index.cjs.map +1 -1
  58. package/dist/cli/index.js +9 -7
  59. package/dist/cli/index.js.map +1 -1
  60. package/dist/docs/api-reference/auth.md +2 -0
  61. package/dist/docs/api-reference/ignite.md +2 -0
  62. package/dist/docs/api-reference/tasks.md +5 -1
  63. package/dist/docs/api-reference/testing.md +2 -0
  64. package/dist/docs/api-reference/tracing.md +18 -0
  65. package/dist/docs/cli/add.md +1 -1
  66. package/dist/docs/core-concepts/background-tasks.md +5 -1
  67. package/dist/docs/core-concepts/file-based-routing.md +2 -0
  68. package/dist/docs/core-concepts/middleware.md +2 -0
  69. package/dist/docs/guides/caching.md +12 -0
  70. package/dist/docs/guides/error-handling.md +2 -0
  71. package/dist/docs/guides/feature-matrix.md +7 -0
  72. package/dist/docs/guides/logging.md +2 -0
  73. package/dist/docs/guides/tracing.md +64 -0
  74. package/dist/docs/index.md +2 -1
  75. package/dist/docs/skills/SKILL.md +5 -3
  76. package/dist/docs/skills/api-surface.md +8 -0
  77. package/dist/docs/skills/auth-internals.md +4 -2
  78. package/dist/docs/skills/pre-flight.md +4 -0
  79. package/dist/docs/skills/routing-rules.md +2 -0
  80. package/dist/docs/skills/tasks-internals.md +10 -2
  81. package/dist/docs/skills/what-not-to-invent.md +2 -0
  82. package/dist/index.cjs +163 -70
  83. package/dist/index.cjs.map +1 -1
  84. package/dist/index.d.cts +5 -14
  85. package/dist/index.d.ts +5 -14
  86. package/dist/index.js +120 -26
  87. package/dist/index.js.map +1 -1
  88. package/dist/pgboss-backend-5DXF4G22.js +16 -0
  89. package/dist/pgboss-backend-KRTFHRNZ.cjs +16 -0
  90. package/dist/pgboss-backend-KRTFHRNZ.cjs.map +1 -0
  91. package/dist/registry/index.json +1 -1
  92. package/dist/tasks/index.cjs +3 -3
  93. package/dist/tasks/index.d.cts +2 -2
  94. package/dist/tasks/index.d.ts +2 -2
  95. package/dist/tasks/index.js +2 -1
  96. package/dist/testing.cjs +16 -14
  97. package/dist/testing.cjs.map +1 -1
  98. package/dist/testing.d.cts +2 -1
  99. package/dist/testing.d.ts +2 -1
  100. package/dist/testing.js +10 -7
  101. package/dist/testing.js.map +1 -1
  102. package/dist/thread-runner.cjs +5 -4
  103. package/dist/thread-runner.cjs.map +1 -1
  104. package/dist/thread-runner.d.cts +1 -1
  105. package/dist/thread-runner.d.ts +1 -1
  106. package/dist/thread-runner.js +4 -2
  107. package/dist/{types-D3QmZgeX.d.ts → types-Bgeqpm-n.d.cts} +12 -1
  108. package/dist/{types-D3QmZgeX.d.cts → types-Bgeqpm-n.d.ts} +12 -1
  109. package/package.json +7 -3
  110. package/dist/chunk-2IDRC7RK.js.map +0 -1
  111. package/dist/chunk-3SWI46YK.js +0 -74
  112. package/dist/chunk-3SWI46YK.js.map +0 -1
  113. package/dist/chunk-6WTMRZS7.cjs.map +0 -1
  114. package/dist/chunk-B6MB6HEG.js.map +0 -1
  115. package/dist/chunk-CGY7JU4Y.cjs.map +0 -1
  116. package/dist/chunk-DGYPIIJE.cjs.map +0 -1
  117. package/dist/chunk-DTMDJGRW.cjs.map +0 -1
  118. package/dist/chunk-EJDZZ4KX.js.map +0 -1
  119. package/dist/chunk-GWMW6XY7.cjs.map +0 -1
  120. package/dist/chunk-H2PVWCWC.cjs.map +0 -1
  121. package/dist/chunk-IEF6AEK3.cjs.map +0 -1
  122. package/dist/chunk-LECHRAU3.js.map +0 -1
  123. package/dist/chunk-OM2XJJWX.js.map +0 -1
  124. package/dist/chunk-QSIP7YLW.cjs.map +0 -1
  125. package/dist/chunk-R6GPQZLI.js.map +0 -1
  126. package/dist/chunk-RPL2IFWK.cjs +0 -77
  127. package/dist/chunk-RPL2IFWK.cjs.map +0 -1
  128. package/dist/pgboss-backend-PQW6I3VF.js +0 -14
  129. package/dist/pgboss-backend-QVXISTLP.cjs +0 -15
  130. package/dist/pgboss-backend-QVXISTLP.cjs.map +0 -1
  131. /package/dist/{chunk-JBOMTZT5.js.map → chunk-3JQWQF2M.js.map} +0 -0
  132. /package/dist/{chunk-O2E7H2XA.js.map → chunk-BCSJOPYH.js.map} +0 -0
  133. /package/dist/{pgboss-backend-PQW6I3VF.js.map → pgboss-backend-5DXF4G22.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-A2QGDWCG.cjs","../src/tasks/index.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACAA,IAAM,MAAA,EAAQ,4CAAA,OAAa,EAAS,CAAA,EAAA,GAAA,CAAO;AAAA,EACzC,QAAA,kBAAU,IAAI,GAAA,CAA4B,CAAA;AAAA,EAC1C,IAAA,EAAM;AACR,CAAA,CAAE,CAAA;AACK,IAAM,aAAA,EAAe,KAAA,CAAM,QAAA;AAQ3B,IAAM,WAAA,EAAiC,CAC5C,gBAAA,EACA,YAAA,EAAA,GACsB;AACtB,EAAA,IAAI,QAAA,EAAuB,CAAC,CAAA;AAC5B,EAAA,IAAI,OAAA;AAEJ,EAAA,GAAA,CAAI,OAAO,iBAAA,IAAqB,UAAA,EAAY;AAC1C,IAAA,QAAA,EAAU,gBAAA;AAAA,EACZ,EAAA,KAAO;AACL,IAAA,QAAA,EAAU,gBAAA;AACV,IAAA,GAAA,CAAI,CAAC,YAAA,EAAc,MAAM,IAAI,KAAA,CAAM,gDAAgD,CAAA;AACnF,IAAA,QAAA,EAAU,YAAA;AAAA,EACZ;AAEA,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,OAAA;AAAA,IACA,IAAA,EAAM;AAAA,EACR,CAAA;AACF,CAAA;AAEO,SAAS,cAAA,CAAe,IAAA,EAAyB;AACtD,EAAA,KAAA,CAAM,KAAA,EAAO,IAAA;AACf;AAGO,IAAM,eAAA,kBAAiB,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAA;AAE5D,MAAA,SAAsB,OAAA,CAAW,IAAA,EAAc,OAAA,EAA2B;AACxE,EAAA,MAAM,OAAA,EAAU,UAAA,CAAuC,cAAc,CAAA;AACrE,EAAA,GAAA,CAAI,CAAC,KAAA,CAAM,KAAA,GAAQ,MAAA,EAAQ,OAAO,MAAA,CAAO,IAAA,EAAM,OAAkB,CAAA;AACjE,EAAA,GAAA,CAAI,CAAC,KAAA,CAAM,IAAA,EAAM;AACf,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,2BAAA,EAA8B,IAAI,CAAA,oEAAA;AAAA,IACpC,CAAA;AAAA,EACF;AACA,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,IAAA,EAAM,OAAkB,CAAA;AAC5C;AAEO,SAAS,YAAA,CAAa,IAAA,EAAc,GAAA,EAA2B;AACpE,EAAA,YAAA,CAAa,GAAA,CAAI,IAAA,EAAM,EAAE,GAAG,GAAA,EAAK,KAAK,CAAC,CAAA;AACzC;AAUO,SAAS,SAAA,CAAA,EAAmE;AACjF,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,YAAA,CAAa,MAAA,CAAO,CAAC,CAAA,CAAE,GAAA,CAAI,CAAC,EAAE,IAAA,EAAM,QAAQ,CAAA,EAAA,GAAA,CAAO,EAAE,IAAA,EAAM,QAAQ,CAAA,CAAE,CAAA;AACzF;ADxBA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sPAAC","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-A2QGDWCG.cjs","sourcesContent":[null,"import { processState } from '../process-state.js';\nimport type { TaskDefinition, TaskOptions } from '../types.js';\n\ntype EnqueueImpl = (name: string, payload: unknown) => Promise<void>;\nconst state = processState('tasks', () => ({\n registry: new Map<string, TaskDefinition>(),\n impl: null as EnqueueImpl | null,\n}));\nexport const taskRegistry = state.registry;\n\ntype HandlerFn<T> = (payload: T) => Promise<void>;\ntype DefineTaskOverload = {\n <T>(handler: HandlerFn<T>): TaskDefinition<T>;\n <T>(options: TaskOptions, handler: HandlerFn<T>): TaskDefinition<T>;\n};\n\nexport const defineTask: DefineTaskOverload = <T>(\n handlerOrOptions: HandlerFn<T> | TaskOptions,\n maybeHandler?: HandlerFn<T>,\n): TaskDefinition<T> => {\n let options: TaskOptions = {};\n let handler: HandlerFn<T>;\n\n if (typeof handlerOrOptions === 'function') {\n handler = handlerOrOptions;\n } else {\n options = handlerOrOptions;\n if (!maybeHandler) throw new Error('[EFC] defineTask: handler function is required');\n handler = maybeHandler;\n }\n\n return {\n handler: handler as (payload: unknown) => Promise<void>,\n options,\n name: '',\n };\n};\n\nexport function setEnqueueImpl(impl: EnqueueImpl): void {\n state.impl = impl;\n}\n\n/** Set inside `{ thread: true }` task threads: forwards enqueue() to the main thread. */\nexport const ENQUEUE_BRIDGE = Symbol.for('efc.enqueueBridge');\n\nexport async function enqueue<T>(name: string, payload: T): Promise<void> {\n const bridge = (globalThis as Record<symbol, unknown>)[ENQUEUE_BRIDGE] as EnqueueImpl | undefined;\n if (!state.impl && bridge) return bridge(name, payload as unknown);\n if (!state.impl) {\n throw new Error(\n `[EFC] Cannot enqueue task \"${name}\": task queue not initialised. Set tasks.backend in ignite() config.`,\n );\n }\n return state.impl(name, payload as unknown);\n}\n\nexport function registerTask(name: string, def: TaskDefinition): void {\n taskRegistry.set(name, { ...def, name });\n}\n\n/**\n * Returns a read-only snapshot of all registered tasks.\n * Each entry contains the task name and its configured options.\n *\n * @example\n * const tasks = listTasks();\n * console.log(tasks.map(t => t.name));\n */\nexport function listTasks(): ReadonlyArray<{ name: string; options: TaskOptions }> {\n return Array.from(taskRegistry.values()).map(({ name, options }) => ({ name, options }));\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getLogger
3
- } from "./chunk-2IDRC7RK.js";
3
+ } from "./chunk-UJ2ISRLP.js";
4
4
 
5
5
  // src/router/scan.ts
6
6
  import fs from "fs";
@@ -113,4 +113,4 @@ function scanDir(dir, base = dir, maxDepth = DEFAULT_MAX_DEPTH, _depth = 0) {
113
113
  export {
114
114
  scanDir
115
115
  };
116
- //# sourceMappingURL=chunk-O2E7H2XA.js.map
116
+ //# sourceMappingURL=chunk-BCSJOPYH.js.map
@@ -1,22 +1,29 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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; }
2
2
 
3
- var _chunkWHBSVYUYcjs = require('./chunk-WHBSVYUY.cjs');
3
+ var _chunk4FQP6QX3cjs = require('./chunk-4FQP6QX3.cjs');
4
4
 
5
5
 
6
6
  var _chunkAGOYTFROcjs = require('./chunk-AGOYTFRO.cjs');
7
7
 
8
8
 
9
9
 
10
+ var _chunkJHCXIYJHcjs = require('./chunk-JHCXIYJH.cjs');
10
11
 
11
12
 
12
13
 
13
- var _chunkQSIP7YLWcjs = require('./chunk-QSIP7YLW.cjs');
14
+
15
+
16
+
17
+ var _chunkURKE3OXNcjs = require('./chunk-URKE3OXN.cjs');
18
+
19
+
20
+ var _chunkPUYBKDYDcjs = require('./chunk-PUYBKDYD.cjs');
14
21
 
15
22
  // src/websocket.ts
16
23
  var _http = require('http'); var _http2 = _interopRequireDefault(_http);
17
24
  var _ws = require('ws');
18
25
  var UPGRADE = /* @__PURE__ */ Symbol.for("express-file-cluster.websocket-upgrade.v1");
19
- var servers = _chunkQSIP7YLWcjs.processState.call(void 0, "websocket-servers", () => /* @__PURE__ */ new WeakMap());
26
+ var servers = _chunkPUYBKDYDcjs.processState.call(void 0, "websocket-servers", () => /* @__PURE__ */ new WeakMap());
20
27
  var isUpgrade = (req) => !!req[UPGRADE];
21
28
  var websocketOnly = (req, res, next) => {
22
29
  const upgrade = req[UPGRADE];
@@ -141,22 +148,22 @@ function attachWebSockets(server, app, options = {}) {
141
148
  alive.add(ws);
142
149
  ws.on("pong", () => alive.add(ws));
143
150
  const context = {
144
- ..._chunkQSIP7YLWcjs.getRequestContext.call(void 0, ),
151
+ ..._chunkURKE3OXNcjs.getRequestContext.call(void 0, ),
145
152
  user: request.user
146
153
  };
147
154
  const emit = ws.emit;
148
- ws.emit = ((event, ...args) => _chunkQSIP7YLWcjs.runWithContext.call(void 0,
155
+ ws.emit = ((event, ...args) => _chunkURKE3OXNcjs.runWithContext.call(void 0,
149
156
  { ...context, queryCounts: /* @__PURE__ */ new Map() },
150
157
  () => Reflect.apply(emit, ws, [event, ...args])
151
158
  ));
152
- ws.on("error", (error) => _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn({ err: error }, "WebSocket error"));
159
+ ws.on("error", (error) => _chunkJHCXIYJHcjs.getLogger.call(void 0, ).warn({ err: error }, "WebSocket error"));
153
160
  const failed = (error) => {
154
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error({ err: error }, "WebSocket handler failed");
161
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).error({ err: error }, "WebSocket handler failed");
155
162
  ws.close(1011, "Internal Server Error");
156
163
  };
157
164
  try {
158
165
  void Promise.resolve(
159
- _chunkQSIP7YLWcjs.runWithContext.call(void 0, context, () => {
166
+ _chunkURKE3OXNcjs.runWithContext.call(void 0, context, () => {
160
167
  wss.emit("connection", ws, incoming);
161
168
  return handler(ws, request);
162
169
  })
@@ -205,6 +212,27 @@ function closeWebSockets(server, timeoutMs = 1e3) {
205
212
  return state.closing;
206
213
  }
207
214
 
215
+ // src/middleware.ts
216
+ function asyncWrap(handler) {
217
+ if (typeof handler !== "function") throw new TypeError("[EFC] Middleware must be a function");
218
+ return (req, res, next) => {
219
+ try {
220
+ void Promise.resolve(handler(req, res, next)).catch(next);
221
+ } catch (error) {
222
+ next(error);
223
+ }
224
+ };
225
+ }
226
+ function asyncErrorWrap(handler) {
227
+ return (error, req, res, next) => {
228
+ try {
229
+ void Promise.resolve(handler(error, req, res, next)).catch(next);
230
+ } catch (failure) {
231
+ next(failure);
232
+ }
233
+ };
234
+ }
235
+
208
236
  // src/router/validate.ts
209
237
  var LOCATIONS = ["params", "query", "body"];
210
238
  function isRequestSchema(value) {
@@ -271,11 +299,6 @@ function validateRequest(schema) {
271
299
 
272
300
  // src/router/mount.ts
273
301
  var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
274
- function asyncWrap(handler) {
275
- return (req, res, next) => {
276
- Promise.resolve(handler(req, res, next)).catch(next);
277
- };
278
- }
279
302
  function namedParams(route) {
280
303
  const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\*/g)].map((m) => m[1]));
281
304
  return (req, _res, next) => {
@@ -313,37 +336,38 @@ async function mountRoutes(app, routes) {
313
336
  app.all(
314
337
  routePath,
315
338
  websocketOnly,
339
+ _chunkURKE3OXNcjs.traceRoute.call(void 0, route.urlPath),
316
340
  ...paramMapper,
317
- ...routeMiddlewares,
341
+ ...routeMiddlewares.map(asyncWrap),
318
342
  ...validation ? [validateRequest(validation)] : [],
319
343
  websocketHandler(mod["WS"])
320
344
  );
321
345
  }
322
346
  const httpOnly = (req, _res, next) => isUpgrade(req) ? next("route") : next();
323
- const implemented = [];
324
- const unimplemented = [];
325
- for (const method of HTTP_METHODS) {
326
- if (typeof mod[method] === "function") {
327
- implemented.push(method);
328
- const methodSchema = schemaFor(schema, method);
329
- const validation = methodSchema ? [validateRequest(methodSchema)] : [];
330
- app[method.toLowerCase()](
331
- routePath,
332
- httpOnly,
333
- ...paramMapper,
334
- ...routeMiddlewares,
335
- ...validation,
336
- asyncWrap(mod[method])
337
- );
338
- } else {
339
- unimplemented.push(method);
340
- }
347
+ const implemented = HTTP_METHODS.filter((method) => typeof mod[method] === "function");
348
+ const unimplemented = HTTP_METHODS.filter((method) => typeof mod[method] !== "function");
349
+ const order = ["HEAD", ...HTTP_METHODS.filter((method) => method !== "HEAD")];
350
+ for (const method of order) {
351
+ if (!implemented.includes(method)) continue;
352
+ const methodSchema = schemaFor(schema, method);
353
+ const validation = methodSchema ? [validateRequest(methodSchema)] : [];
354
+ app[method.toLowerCase()](
355
+ routePath,
356
+ httpOnly,
357
+ _chunkURKE3OXNcjs.traceRoute.call(void 0, route.urlPath),
358
+ ...paramMapper,
359
+ ...routeMiddlewares.map(asyncWrap),
360
+ ...validation,
361
+ asyncWrap(mod[method])
362
+ );
341
363
  }
342
364
  if (implemented.length > 0 && unimplemented.length > 0) {
343
365
  const allowHeader = implemented.join(", ");
344
366
  app.all(routePath, (req, res, next) => {
345
367
  if (isUpgrade(req)) return next();
346
368
  if (unimplemented.includes(req.method)) {
369
+ _chunkURKE3OXNcjs.traceRoute.call(void 0, route.urlPath)(req, res, () => {
370
+ });
347
371
  res.set("Allow", allowHeader).status(405).json({ error: "Method Not Allowed" });
348
372
  } else {
349
373
  next();
@@ -582,7 +606,7 @@ async function generateOpenAPI(input, options = {}) {
582
606
  if (!input.trim() || !_fs2.default.existsSync(input) || !_fs2.default.statSync(input).isDirectory())
583
607
  throw new Error("[EFC] OpenAPI apiDir must be an existing directory");
584
608
  routes = [];
585
- for (const route of _chunkWHBSVYUYcjs.scanDir.call(void 0, _path2.default.resolve(input))) {
609
+ for (const route of _chunk4FQP6QX3cjs.scanDir.call(void 0, _path2.default.resolve(input))) {
586
610
  const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(route.filePath)));
587
611
  routes.push({
588
612
  ...route,
@@ -774,9 +798,11 @@ function createHttpApp(config) {
774
798
  (_key, value) => typeof value === "bigint" ? value.toString() : value
775
799
  );
776
800
  app.use((_req, _res, next) => {
777
- _chunkQSIP7YLWcjs.runWithContext.call(void 0, {}, next);
801
+ _chunkURKE3OXNcjs.runWithContext.call(void 0, {}, next);
778
802
  });
779
- app.use(_chunkQSIP7YLWcjs.requestLogger.call(void 0, ));
803
+ if (config.tracing && (config.tracing === true || config.tracing.http !== false))
804
+ app.use(_chunkURKE3OXNcjs.httpTracing.call(void 0, ));
805
+ app.use(_chunkJHCXIYJHcjs.requestLogger.call(void 0, ));
780
806
  if (config.requestTimeout) {
781
807
  const ms = config.requestTimeout;
782
808
  app.use((_req, res, next) => {
@@ -799,38 +825,39 @@ function createHttpApp(config) {
799
825
  app.use(_express2.default.urlencoded({ extended: true }));
800
826
  app.use(_cookieparser2.default.call(void 0, ));
801
827
  for (const mw of globalMiddlewares) {
802
- app.use(mw);
828
+ app.use(asyncWrap(mw));
803
829
  }
804
830
  return app;
805
831
  }
806
832
  function mountErrorHandler(app, onError) {
833
+ app.use(_chunkURKE3OXNcjs.traceHttpError);
807
834
  if (onError) {
808
- app.use(onError);
809
- } else {
810
- app.use(
811
- (err, _req, res, _next) => {
812
- if (res.headersSent) {
813
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn({ err }, "Error after the response was sent");
814
- return;
815
- }
816
- const status = _optionalChain([err, 'optionalAccess', _43 => _43.statusCode]);
817
- const duckTyped = err instanceof Error && typeof status === "number" && status >= 400 && status < 500 ? err : null;
818
- if (_chunkAGOYTFROcjs.isHttpError.call(void 0, err)) {
819
- const issues = err.issues;
820
- res.status(err.statusCode).json({
821
- error: err.message,
822
- statusCode: err.statusCode,
823
- ...issues !== void 0 && { issues }
824
- });
825
- } else if (duckTyped) {
826
- res.status(duckTyped.statusCode).json({ error: duckTyped.message, statusCode: duckTyped.statusCode });
827
- } else {
828
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error({ err }, "Unhandled error");
829
- res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
830
- }
831
- }
832
- );
835
+ app.use(asyncErrorWrap(onError));
833
836
  }
837
+ app.use(
838
+ (err, _req, res, _next) => {
839
+ if (res.headersSent) {
840
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).warn({ err }, "Error after the response was sent");
841
+ if (!res.writableEnded) res.destroy();
842
+ return;
843
+ }
844
+ const status = _optionalChain([err, 'optionalAccess', _43 => _43.statusCode]);
845
+ const duckTyped = err instanceof Error && typeof status === "number" && status >= 400 && status < 500 ? err : null;
846
+ if (_chunkAGOYTFROcjs.isHttpError.call(void 0, err)) {
847
+ const issues = err.issues;
848
+ res.status(err.statusCode).json({
849
+ error: err.message,
850
+ statusCode: err.statusCode,
851
+ ...issues !== void 0 && { issues }
852
+ });
853
+ } else if (duckTyped) {
854
+ res.status(duckTyped.statusCode).json({ error: duckTyped.message, statusCode: duckTyped.statusCode });
855
+ } else {
856
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).error({ err }, "Unhandled error");
857
+ res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
858
+ }
859
+ }
860
+ );
834
861
  }
835
862
 
836
863
 
@@ -842,4 +869,4 @@ function mountErrorHandler(app, onError) {
842
869
 
843
870
 
844
871
  exports.attachWebSockets = attachWebSockets; exports.closeWebSockets = closeWebSockets; exports.mountRoutes = mountRoutes; exports.generateOpenAPI = generateOpenAPI; exports.mountOpenAPI = mountOpenAPI; exports.createHttpApp = createHttpApp; exports.mountErrorHandler = mountErrorHandler;
845
- //# sourceMappingURL=chunk-DGYPIIJE.cjs.map
872
+ //# sourceMappingURL=chunk-BJR42CN3.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-BJR42CN3.cjs","../src/websocket.ts","../src/middleware.ts","../src/router/validate.ts","../src/router/mount.ts","../src/openapi.ts","../src/http-app.ts"],"names":["path"],"m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AA;AACyC,IAAA;AACjD,EAAA;AAK8B,EAAA;AACL,IAAA;AACxB,EAAA;AACyE,EAAA;AACnD,IAAA;AACA,EAAA;AAEI,EAAA;AACP,IAAA;AACW,IAAA;AACI,MAAA;AAC2D,QAAA;AACrF,MAAA;AACiC,MAAA;AACd,MAAA;AACD,MAAA;AAClB,MAAA;AACN,IAAA;AACH,EAAA;AAEkC,EAAA;AACR,EAAA;AAEkE,IAAA;AACH,IAAA;AACjE,IAAA;AACxB,EAAA;AAEsB,EAAA;AACwB,EAAA;AACxB,EAAA;AAEc,EAAA;AACb,IAAA;AACvB,EAAA;AAEO,EAAA;AACT;AAKQ;AACgB,EAAA;AACT,EAAA;AACoB,IAAA;AACjC,EAAA;AACI,EAAA;AAC2F,IAAA;AAEtE,MAAA;AAC0C,QAAA;AACzB,QAAA;AACpC,QAAA;AACF,MAAA;AAKyD,MAAA;AAInD,MAAA;AAEgB,MAAA;AAEyB,QAAA;AACb,QAAA;AACnB,UAAA;AACK,UAAA;AACqB,UAAA;AACtC,QAAA;AACmB,MAAA;AAGkD,QAAA;AACjE,MAAA;AACuC,QAAA;AAC4B,QAAA;AAC1E,MAAA;AACF,IAAA;AACF,EAAA;AACF;ANkvB6K;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-BJR42CN3.cjs","sourcesContent":[null,"import http from 'node:http';\nimport type { Socket } from 'node:net';\nimport type { Express, Request, RequestHandler, Response } from 'express';\nimport { WebSocketServer, WebSocket } from 'ws';\nimport { getRequestContext, runWithContext } from './context.js';\nimport { getLogger } from './logger.js';\nimport { processState } from './process-state.js';\n\nexport type WebSocketHandler = (socket: WebSocket, request: Request) => void | Promise<void>;\nexport interface WebSocketOptions {\n /** Default 1 MiB. Compression is disabled. */\n maxPayload?: number;\n /** Browser origins; default is same-origin. Clients without Origin are allowed. */\n origins?: string[];\n /** Default 30 seconds; 0 disables heartbeat. */\n heartbeatIntervalMs?: number;\n /** Default 10 seconds to finish upgrade middleware. */\n handshakeTimeoutMs?: number;\n}\ninterface Upgrade {\n options: WebSocketOptions;\n accepted: boolean;\n accept: (handler: WebSocketHandler, req: Request, res: Response) => void;\n}\nconst UPGRADE = Symbol.for('express-file-cluster.websocket-upgrade.v1');\ntype UpgradeRequest = Request & { [UPGRADE]?: Upgrade };\ninterface State {\n wss: WebSocketServer;\n pending: Set<Socket>;\n stopHeartbeat: () => void;\n closing?: Promise<void>;\n}\nconst servers = processState('websocket-servers', () => new WeakMap<http.Server, State>());\nexport const isUpgrade = (req: Request): boolean => !!(req as UpgradeRequest)[UPGRADE];\n\n/** Gate mounted before file middleware: ordinary HTTP continues to its own handler. */\nexport const websocketOnly: RequestHandler = (req, res, next) => {\n const upgrade = (req as UpgradeRequest)[UPGRADE];\n if (!upgrade) return next('route');\n const origin = req.headers.origin;\n if (origin !== undefined) {\n let valid = false;\n try {\n const parsed = new URL(origin);\n valid =\n parsed.origin === origin &&\n ['http:', 'https:'].includes(parsed.protocol) &&\n (upgrade.options.origins\n ? upgrade.options.origins.includes(origin)\n : origin === `${req.protocol}://${req.get('host')}`);\n } catch {\n /* malformed and opaque origins are refused */\n }\n if (!valid) {\n res.status(403).json({ error: 'WebSocket origin rejected' });\n return;\n }\n }\n next();\n};\nexport function websocketHandler(handler: WebSocketHandler): RequestHandler {\n return (req, res) => {\n (req as UpgradeRequest)[UPGRADE]!.accept(handler, req, res);\n };\n}\n\n/** Attach upgrade handling to an EFC HTTP app/server (also useful with createTestApp). */\nexport function attachWebSockets(\n server: http.Server,\n app: Express,\n options: WebSocketOptions = {},\n): WebSocketServer {\n if (servers.has(server)) throw new Error('[EFC] WebSockets already attached to this server');\n const maxPayload = options.maxPayload ?? 1024 * 1024;\n const heartbeat = options.heartbeatIntervalMs ?? 30000;\n const timeout = options.handshakeTimeoutMs ?? 10000;\n for (const [name, value, minimum] of [\n ['maxPayload', maxPayload, 1],\n ['heartbeatIntervalMs', heartbeat, 0],\n ['handshakeTimeoutMs', timeout, 1],\n ] as const) {\n // ws coerces maxPayload to int32; Node timers also have a signed int32 ceiling.\n if (!Number.isSafeInteger(value) || value < minimum || value > 0x7fffffff)\n throw new Error(`[EFC] websocket.${name} must be an integer from ${minimum} to 2147483647`);\n }\n for (const origin of options.origins ?? []) {\n const parsed = new URL(origin);\n if (parsed.origin !== origin || !['http:', 'https:'].includes(parsed.protocol))\n throw new Error('[EFC] websocket.origins must contain HTTP(S) origins');\n }\n const wss = new WebSocketServer({ noServer: true, maxPayload, perMessageDeflate: false });\n // ws writes the 101 response itself; preserve ordinary middleware headers without\n // allowing them to replace protocol framing/negotiation headers.\n const reserved = new Set([\n 'upgrade',\n 'connection',\n 'sec-websocket-accept',\n 'sec-websocket-protocol',\n 'sec-websocket-extensions',\n 'content-length',\n 'transfer-encoding',\n 'content-type',\n ]);\n wss.on('headers', (headers, incoming) => {\n const response = (incoming as Request).res;\n for (const [name, value] of Object.entries(response?.getHeaders() ?? {})) {\n if (reserved.has(name.toLowerCase()) || value === undefined) continue;\n for (const entry of Array.isArray(value) ? value : [value])\n headers.push(name + ': ' + String(entry));\n }\n });\n const alive = new WeakSet<WebSocket>();\n const interval = heartbeat\n ? setInterval(() => {\n for (const client of wss.clients) {\n if (!alive.has(client)) {\n client.terminate();\n continue;\n }\n alive.delete(client);\n if (client.readyState === WebSocket.OPEN) client.ping();\n }\n }, heartbeat)\n : undefined;\n interval?.unref();\n const state: State = {\n wss,\n pending: new Set(),\n stopHeartbeat: () => {\n if (interval) clearInterval(interval);\n },\n };\n servers.set(server, state);\n server.on('upgrade', (incoming, socket, head) => {\n if (state.closing) {\n socket.destroy();\n return;\n }\n const req = incoming as UpgradeRequest;\n const response = new http.ServerResponse(incoming) as Response;\n try {\n response.assignSocket(socket as Socket);\n } catch {\n // A pipelined upgrade can arrive while the preceding HTTP response still\n // owns this socket. Reject the connection instead of crashing the worker.\n socket.destroy();\n return;\n }\n state.pending.add(socket as Socket);\n const onError = () => socket.destroy();\n socket.on('error', onError);\n const timer = setTimeout(() => {\n if (!response.headersSent)\n response.status(408).json({ error: 'WebSocket upgrade timed out' });\n socket.end();\n }, timeout);\n timer.unref();\n socket.once('close', () => {\n state.pending.delete(socket as Socket);\n clearTimeout(timer);\n socket.removeListener('error', onError);\n });\n const upgrade: Upgrade = {\n options,\n accepted: false,\n accept(handler, request, res) {\n if (upgrade.accepted || res.headersSent || socket.destroyed || state.closing) return;\n upgrade.accepted = true;\n clearTimeout(timer);\n wss.handleUpgrade(incoming, socket, head, (ws) => {\n state.pending.delete(socket as Socket);\n res.detachSocket(socket as Socket);\n res.statusCode = 101;\n res.emit('finish'); // Finish HTTP accounting and clear requestTimeout without writing HTTP bytes.\n socket.removeListener('error', onError);\n alive.add(ws);\n ws.on('pong', () => alive.add(ws));\n const context = {\n ...getRequestContext(),\n user: (request as Request & { user?: Record<string, unknown> }).user,\n };\n const emit = ws.emit;\n ws.emit = ((event: string | symbol, ...args: unknown[]) =>\n runWithContext({ ...context, queryCounts: new Map() }, () =>\n Reflect.apply(emit, ws, [event, ...args]),\n )) as typeof ws.emit;\n ws.on('error', (error) => getLogger().warn({ err: error }, 'WebSocket error'));\n const failed = (error: unknown) => {\n getLogger().error({ err: error }, 'WebSocket handler failed');\n ws.close(1011, 'Internal Server Error');\n };\n try {\n void Promise.resolve(\n runWithContext(context, () => {\n wss.emit('connection', ws, incoming);\n return handler(ws, request);\n }),\n ).catch(failed);\n } catch (error) {\n failed(error);\n }\n });\n },\n };\n req[UPGRADE] = upgrade;\n response.once('finish', () => {\n clearTimeout(timer);\n if (!upgrade.accepted) socket.end();\n });\n app(req, response);\n });\n // HTTP server.close() alone does not drain upgraded sockets.\n const close = server.close;\n server.close = function (callback?: (error?: Error) => void) {\n void closeWebSockets(server);\n return close.call(this, callback);\n };\n server.once('close', () => {\n state.stopHeartbeat();\n });\n return wss;\n}\n\n/** Close upgraded sockets with 1001, then terminate peers that do not acknowledge. */\nexport function closeWebSockets(server: http.Server, timeoutMs = 1000): Promise<void> {\n const state = servers.get(server);\n if (!state) return Promise.resolve();\n if (state.closing) return state.closing;\n state.stopHeartbeat();\n state.closing = new Promise<void>((resolve) => {\n for (const socket of state.pending) socket.destroy();\n state.pending.clear();\n const timer = setTimeout(() => {\n for (const client of state.wss.clients) client.terminate();\n }, timeoutMs);\n timer.unref();\n state.wss.close(() => {\n clearTimeout(timer);\n resolve();\n });\n for (const client of state.wss.clients) client.close(1001, 'Server shutting down');\n });\n return state.closing;\n}\n","import type { RequestHandler, ErrorRequestHandler } from 'express';\n\n/** Express 4 does not observe returned promises. Keep its next/skip semantics. */\nexport function asyncWrap(handler: RequestHandler): RequestHandler {\n if (typeof handler !== 'function') throw new TypeError('[EFC] Middleware must be a function');\n return (req, res, next) => {\n try {\n void Promise.resolve(handler(req, res, next)).catch(next);\n } catch (error) {\n next(error);\n }\n };\n}\nexport function asyncErrorWrap(handler: ErrorRequestHandler): ErrorRequestHandler {\n return (error, req, res, next) => {\n try {\n void Promise.resolve(handler(error, req, res, next)).catch(next);\n } catch (failure) {\n next(failure);\n }\n };\n}\n","import type { Request, RequestHandler } from 'express';\nimport type { RequestSchema, RouteSchema, ValidationIssue, Validator } from '../types.js';\n\nconst LOCATIONS = ['params', 'query', 'body'] as const;\ntype Location = (typeof LOCATIONS)[number];\n\ninterface StandardResult {\n value?: unknown;\n issues?: ReadonlyArray<{\n message: string;\n path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n }>;\n}\n\nfunction isRequestSchema(value: unknown): value is RequestSchema {\n return (\n value != null &&\n typeof value === 'object' &&\n LOCATIONS.some((loc) => loc in (value as Record<string, unknown>))\n );\n}\n\n/** Picks the schema for `method`: a method-keyed entry wins over a file-wide one. */\nexport function schemaFor(\n schema: RouteSchema | undefined,\n method: string,\n): RequestSchema | undefined {\n if (!schema) return undefined;\n const byMethod = (schema as Record<string, unknown>)[method];\n if (isRequestSchema(byMethod)) return byMethod;\n return isRequestSchema(schema) ? schema : undefined;\n}\n\ntype IssuePath = ReadonlyArray<PropertyKey | { key: PropertyKey }> | undefined;\n\nfunction pathToString(path: IssuePath): string {\n if (!path) return '';\n return path\n .map((p) => (typeof p === 'object' && p !== null && 'key' in p ? p.key : p))\n .map(String)\n .join('.');\n}\n\n// Standard Schema (zod >=3.24, valibot, arktype, ...) first; plain zod-style\n// safeParse as a fallback so older zod 3 releases work too.\nasync function run(validator: Validator, input: unknown): Promise<StandardResult> {\n const std = (validator as { '~standard'?: { validate: (v: unknown) => unknown } })['~standard'];\n if (std && typeof std.validate === 'function') {\n return (await std.validate(input)) as StandardResult;\n }\n const v = validator as {\n safeParseAsync?: (x: unknown) => Promise<unknown>;\n safeParse?: (x: unknown) => unknown;\n };\n const parse = v.safeParseAsync ?? v.safeParse;\n if (typeof parse !== 'function') {\n throw new Error('[EFC] Route schema entries must be Standard Schema validators (e.g. zod)');\n }\n const r = (await parse.call(validator, input)) as {\n success: boolean;\n data?: unknown;\n error?: { issues: Array<{ message: string; path: PropertyKey[] }> };\n };\n return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: 'Invalid' }] };\n}\n\n/**\n * Validates params/query/body against the route's schema. On success the parsed\n * output replaces the raw input (so coercions and defaults apply); on failure\n * responds 400 with every issue across all locations.\n */\nexport function validateRequest(schema: RequestSchema): RequestHandler {\n return (req, res, next) => {\n void (async () => {\n const issues: ValidationIssue[] = [];\n const parsed: Partial<Record<Location, unknown>> = {};\n\n for (const location of LOCATIONS) {\n const validator = schema[location];\n if (!validator) continue;\n const result = await run(validator, req[location]);\n if (result.issues) {\n for (const issue of result.issues) {\n issues.push({ location, path: pathToString(issue.path), message: issue.message });\n }\n } else {\n parsed[location] = result.value;\n }\n }\n\n if (issues.length > 0) {\n res.status(400).json({ error: 'Validation failed', statusCode: 400, issues });\n return;\n }\n\n for (const location of LOCATIONS) {\n if (location in parsed) {\n // req.query is a getter in some Express setups — define rather than assign.\n Object.defineProperty(req as Request, location, {\n value: parsed[location],\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n next();\n })().catch(next);\n };\n}\n","import { asyncWrap } from '../middleware.js';\nimport type { IRouter, RequestHandler } from 'express';\nimport type { MountedRoute, RouteMeta, RouteEntry, RouteSchema } from '../types.js';\nimport { schemaFor, validateRequest } from './validate.js';\nimport { isUpgrade, websocketOnly, websocketHandler, type WebSocketHandler } from '../websocket.js';\n\nimport { traceRoute } from '../tracing.js';\n\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const;\ntype HttpMethod = (typeof HTTP_METHODS)[number];\n\n/**\n * For RegExp-mounted (catch-all) routes, Express exposes captures as params[0..n].\n * Rename them to the segment names from the file path; catch-alls become string\n * arrays (`[...slug]` → `['a', 'b']`), absent optional segments become undefined.\n */\nfunction namedParams(route: RouteEntry): RequestHandler {\n const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\\*/g)].map((m) => m[1]!));\n return (req, _res, next) => {\n // Express has already decoded req.params. Read the raw captures so splitting\n // happens before decoding (an encoded slash belongs to a single segment).\n const captures = route.pattern!.exec(req.path);\n const named: Record<string, unknown> = {};\n route.params.forEach((name, i) => {\n const value = captures?.[i + 1];\n if (value === undefined || value === '') {\n named[name] = catchAlls.has(name) ? [] : undefined;\n } else if (catchAlls.has(name)) {\n named[name] = value.split('/').filter(Boolean).map(decodeURIComponent);\n } else {\n named[name] = decodeURIComponent(value);\n }\n });\n req.params = named as typeof req.params;\n next();\n };\n}\n\nexport async function mountRoutes(app: IRouter, routes: RouteEntry[]): Promise<MountedRoute[]> {\n const mounted: MountedRoute[] = [];\n\n for (const route of routes) {\n const mod = (await import(route.filePath)) as Record<string, unknown>;\n const routeMiddlewares: RequestHandler[] = Array.isArray(mod['middlewares'])\n ? (mod['middlewares'] as RequestHandler[])\n : [];\n\n const raw = mod['meta'];\n const meta: RouteMeta | undefined =\n raw != null && typeof raw === 'object' && !Array.isArray(raw)\n ? (raw as RouteMeta)\n : undefined;\n\n const schema =\n mod['schema'] != null && typeof mod['schema'] === 'object'\n ? (mod['schema'] as RouteSchema)\n : undefined;\n\n const routePath = route.pattern ?? route.urlPath;\n const paramMapper = route.pattern ? [namedParams(route)] : [];\n\n const websocket = typeof mod['WS'] === 'function';\n if (mod['WS'] !== undefined && !websocket)\n throw new Error(`[EFC] WS must be a function: ${route.filePath}`);\n if (websocket) {\n const validation = schemaFor(schema, 'WS');\n app.all(\n routePath,\n websocketOnly,\n traceRoute(route.urlPath),\n ...paramMapper,\n ...routeMiddlewares.map(asyncWrap),\n ...(validation ? [validateRequest(validation)] : []),\n websocketHandler(mod['WS'] as WebSocketHandler),\n );\n }\n const httpOnly: RequestHandler = (req, _res, next) => (isUpgrade(req) ? next('route') : next());\n const implemented = HTTP_METHODS.filter((method) => typeof mod[method] === 'function');\n const unimplemented = HTTP_METHODS.filter((method) => typeof mod[method] !== 'function');\n // Express GET also matches HEAD, so explicit HEAD must be registered first.\n const order = ['HEAD', ...HTTP_METHODS.filter((method) => method !== 'HEAD')] as HttpMethod[];\n for (const method of order) {\n if (!implemented.includes(method)) continue;\n const methodSchema = schemaFor(schema, method);\n const validation = methodSchema ? [validateRequest(methodSchema)] : [];\n app[method.toLowerCase() as Lowercase<HttpMethod>](\n routePath,\n httpOnly,\n traceRoute(route.urlPath),\n ...paramMapper,\n ...routeMiddlewares.map(asyncWrap),\n ...validation,\n asyncWrap(mod[method] as RequestHandler),\n );\n }\n\n if (implemented.length > 0 && unimplemented.length > 0) {\n const allowHeader = implemented.join(', ');\n app.all(routePath, (req, res, next) => {\n if (isUpgrade(req)) return next();\n if ((unimplemented as string[]).includes(req.method)) {\n traceRoute(route.urlPath)(req, res, () => {});\n res.set('Allow', allowHeader).status(405).json({ error: 'Method Not Allowed' });\n } else {\n next();\n }\n });\n }\n\n mounted.push({\n ...route,\n methods: implemented,\n ...(meta !== undefined && { meta }),\n ...(schema && { schema }),\n ...(websocket && { websocket }),\n });\n }\n\n return mounted;\n}\n\nexport { asyncWrap };\n","import { Router, type Express, type Request, type Response } from 'express';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { scanDir } from './router/scan.js';\nimport type { MountedRoute, Validator } from './types.js';\nimport { schemaFor } from './router/validate.js';\n\nexport type JSONSchema = boolean | Record<string, unknown>;\nexport interface OpenAPIOptions {\n /** Absolute static URL for the document. Default /openapi.json. */\n path?: string;\n info?: { title: string; version: string; description?: string };\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n /** Adapter for validators without Standard JSON Schema support. */\n schemaToJSONSchema?: (validator: Validator) => JSONSchema | Promise<JSONSchema>;\n}\nexport interface OpenAPIDocument {\n openapi: '3.1.0';\n info: { title: string; version: string; description?: string };\n paths: Record<string, Record<string, unknown>>;\n components: Record<string, unknown> & { schemas: Record<string, JSONSchema> };\n servers?: Array<{ url: string; description?: string }>;\n}\nconst pointer = (value: string) => value.replace(/~/g, '~0').replace(/\\//g, '~1');\nconst record = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n/** Expand optional URL segments: OpenAPI requires every path parameter to be present. */\nfunction variants(url: string): string[] {\n let paths = [''];\n for (const segment of url.split('/').filter(Boolean)) {\n const optional = /^:([\\w$]+)(\\*)?\\?$/.test(segment);\n const formatted = segment.replace(/:([\\w$]+)\\*?\\??/g, '{$1}');\n paths = paths.flatMap((path) =>\n optional ? [path + '/' + formatted, path] : [path + '/' + formatted],\n );\n if (paths.length > 256) throw new Error('[EFC] OpenAPI: too many optional path variants');\n }\n // Express greedily fills earlier optional parameters. Keep that binding when\n // several expansions describe the same URL shape, which OAS cannot duplicate.\n const shapes = new Set<string>();\n return paths\n .map((path) => path || '/')\n .filter((path) => {\n const shape = path.replace(/\\{[^}]+\\}/g, '{}');\n if (shapes.has(shape)) return false;\n shapes.add(shape);\n return true;\n });\n}\nfunction rebase(value: unknown, root: string, resource = false): unknown {\n if (Array.isArray(value)) return value.map((child) => rebase(child, root, resource));\n const object = record(value);\n if (!object) return value;\n resource = resource || typeof object.$id === 'string';\n const maps = new Set([\n 'properties',\n 'patternProperties',\n '$defs',\n 'definitions',\n 'dependentSchemas',\n ]);\n const children = new Set([\n 'items',\n 'additionalProperties',\n 'contains',\n 'propertyNames',\n 'not',\n 'if',\n 'then',\n 'else',\n 'unevaluatedProperties',\n 'unevaluatedItems',\n 'contentSchema',\n 'allOf',\n 'anyOf',\n 'oneOf',\n 'prefixItems',\n ]);\n return Object.fromEntries(\n Object.entries(object).map(([key, child]) => {\n if (\n !resource &&\n (key === '$ref' || key === '$dynamicRef') &&\n typeof child === 'string' &&\n (child === '#' || child.startsWith('#/'))\n )\n return [key, root + child.slice(1)];\n if (maps.has(key) && record(child))\n return [\n key,\n Object.fromEntries(\n Object.entries(child as Record<string, unknown>).map(([name, schema]) => [\n name,\n rebase(schema, root, resource),\n ]),\n ),\n ];\n return [key, children.has(key) ? rebase(child, root, resource) : child];\n }),\n );\n}\n\ninterface ParameterField {\n schema: JSONSchema;\n object: boolean;\n array: boolean;\n}\ninterface ParameterShape {\n properties: Map<string, ParameterField>;\n required: Set<string>;\n}\n\nfunction parameterObject(schema: JSONSchema | undefined, rootRef: string): ParameterShape {\n const empty = (): ParameterShape => ({ properties: new Map(), required: new Set() });\n if (schema === undefined) return empty();\n const target = (ref: string): unknown => {\n if (!ref.startsWith('#/')) throw new Error('parameter schemas need local JSON pointers');\n let value: unknown = schema;\n for (const part of ref.slice(2).split('/')) {\n const key = part.replace(/~1/g, '/').replace(/~0/g, '~');\n const object = record(value);\n // Arrays occur in pointers into anyOf/allOf/oneOf branches.\n value = Array.isArray(value)\n ? value[Number(key)]\n : object && Object.hasOwn(object, key)\n ? object[key]\n : undefined;\n }\n return value;\n };\n const hasType = (value: unknown, type: 'object' | 'array', seen = new Set<string>()): boolean => {\n const object = record(value);\n if (!object) return false;\n if (object.type === type || (type === 'object' && object.properties)) return true;\n if (typeof object.$ref === 'string' && object.$ref.startsWith('#/') && !seen.has(object.$ref)) {\n return hasType(target(object.$ref), type, new Set([...seen, object.$ref]));\n }\n return ['allOf', 'anyOf', 'oneOf'].some(\n (key) =>\n Array.isArray(object[key]) &&\n object[key].some((child: unknown) => hasType(child, type, seen)),\n );\n };\n const merge = (shapes: ParameterShape[], mode: 'allOf' | 'anyOf'): ParameterShape => {\n const result = empty();\n const names = new Set(shapes.flatMap((shape) => [...shape.properties.keys()]));\n for (const name of names) {\n const fields = shapes.flatMap((shape) => {\n const field = shape.properties.get(name);\n return field ? [field] : [];\n });\n result.properties.set(name, {\n schema:\n fields.length === 1 ? fields[0]!.schema : { [mode]: fields.map((field) => field.schema) },\n object: fields.some((field) => field.object),\n array: fields.some((field) => field.array),\n });\n }\n const required = new Set(shapes.flatMap((shape) => [...shape.required]));\n for (const name of required) {\n if (mode === 'allOf' || shapes.every((shape) => shape.required.has(name)))\n result.required.add(name);\n }\n return result;\n };\n const visit = (value: unknown, fragment: string, seen: Set<string>): ParameterShape => {\n const object = record(value);\n if (!object) throw new Error('query/params schemas must describe objects');\n const shapes: ParameterShape[] = [];\n const properties = record(object.properties);\n if (properties || object.type === 'object' || Array.isArray(object.required)) {\n const direct = empty();\n for (const [name, child] of Object.entries(properties ?? {})) {\n direct.properties.set(name, {\n schema: { $ref: rootRef + fragment + '/properties/' + pointer(name) },\n object: hasType(child, 'object'),\n array: hasType(child, 'array'),\n });\n }\n if (Array.isArray(object.required)) {\n for (const name of object.required) if (typeof name === 'string') direct.required.add(name);\n }\n shapes.push(direct);\n }\n if (typeof object.$ref === 'string') {\n if (seen.has(object.$ref)) throw new Error('cyclic parameter object reference');\n shapes.push(\n visit(target(object.$ref), object.$ref.slice(1), new Set([...seen, object.$ref])),\n );\n }\n for (const key of ['allOf', 'anyOf', 'oneOf'] as const) {\n const branches = object[key];\n if (!Array.isArray(branches) || !branches.length) continue;\n shapes.push(\n merge(\n branches.map((branch, index) => visit(branch, fragment + '/' + key + '/' + index, seen)),\n key === 'allOf' ? 'allOf' : 'anyOf',\n ),\n );\n }\n if (!shapes.length)\n throw new Error(\n 'query/params schemas must describe objects; use explicit openapi.parameters for other shapes',\n );\n return merge(shapes, 'allOf');\n };\n return visit(schema, '', new Set());\n}\n\n/** Missing JSON bodies are {} after Express's parsers. Unknown external refs\n * remain conservative; explicit requestBody metadata can override requiredness. */\nfunction acceptsEmptyObject(\n schema: JSONSchema,\n root = schema,\n seen = new Set<string>(),\n): boolean | undefined {\n if (typeof schema === 'boolean') return schema;\n if (schema !== root && typeof schema.$id === 'string') {\n root = schema;\n seen = new Set();\n }\n const results: Array<boolean | undefined> = [];\n if (typeof schema.$dynamicRef === 'string') results.push(undefined);\n if (schema.type !== undefined) {\n const types = Array.isArray(schema.type) ? schema.type : [schema.type];\n results.push(types.includes('object'));\n }\n const isEmpty = (value: unknown) => !!record(value) && Object.keys(value as object).length === 0;\n if ('const' in schema) results.push(isEmpty(schema.const));\n if (Array.isArray(schema.enum)) results.push(schema.enum.some(isEmpty));\n if (Array.isArray(schema.required)) results.push(schema.required.length === 0);\n if (typeof schema.minProperties === 'number') results.push(schema.minProperties <= 0);\n if (typeof schema.$ref === 'string') {\n const ref = schema.$ref;\n if ((!ref.startsWith('#/') && ref !== '#') || seen.has(ref)) results.push(undefined);\n else {\n let target: unknown = root;\n for (const part of ref === '#' ? [] : ref.slice(2).split('/')) {\n const key = part.replace(/~1/g, '/').replace(/~0/g, '~');\n target = Array.isArray(target) ? target[Number(key)] : record(target)?.[key];\n }\n results.push(\n typeof target === 'boolean' || record(target)\n ? acceptsEmptyObject(target as JSONSchema, root, new Set([...seen, ref]))\n : undefined,\n );\n }\n }\n for (const key of ['allOf', 'anyOf', 'oneOf'] as const) {\n if (!Array.isArray(schema[key])) continue;\n const values = schema[key].map((child: JSONSchema) => acceptsEmptyObject(child, root, seen));\n if (key === 'allOf')\n results.push(values.includes(false) ? false : values.includes(undefined) ? undefined : true);\n if (key === 'anyOf')\n results.push(values.includes(true) ? true : values.includes(undefined) ? undefined : false);\n if (key === 'oneOf')\n results.push(\n values.filter((value) => value === true).length > 1\n ? false\n : values.includes(undefined)\n ? undefined\n : values.filter((value) => value === true).length === 1,\n );\n }\n if (typeof schema.not === 'boolean' || record(schema.not)) {\n const value = acceptsEmptyObject(schema.not as JSONSchema, root, seen);\n results.push(value === undefined ? undefined : !value);\n }\n if (typeof schema.if === 'boolean' || record(schema.if)) {\n const condition = acceptsEmptyObject(schema.if as JSONSchema, root, seen);\n const branch = (key: 'then' | 'else') =>\n typeof schema[key] === 'boolean' || record(schema[key])\n ? acceptsEmptyObject(schema[key] as JSONSchema, root, seen)\n : true;\n results.push(\n condition === undefined\n ? branch('then') === branch('else')\n ? branch('then')\n : undefined\n : branch(condition ? 'then' : 'else'),\n );\n }\n return results.includes(false) ? false : results.includes(undefined) ? undefined : true;\n}\n\n/** Generate a document from the same mounted route exports used by the HTTP router. */\nexport async function generateOpenAPI(\n input: MountedRoute[] | string,\n options: OpenAPIOptions & { basePath?: string } = {},\n): Promise<OpenAPIDocument> {\n let routes: MountedRoute[];\n if (typeof input === 'string') {\n if (!input.trim() || !fs.existsSync(input) || !fs.statSync(input).isDirectory())\n throw new Error('[EFC] OpenAPI apiDir must be an existing directory');\n routes = [];\n for (const route of scanDir(path.resolve(input))) {\n const mod = (await import(route.filePath)) as Record<string, unknown>;\n routes.push({\n ...route,\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].filter(\n (method) => typeof mod[method] === 'function',\n ),\n ...(record(mod.meta) && { meta: mod.meta as NonNullable<MountedRoute['meta']> }),\n ...(record(mod.schema) && { schema: mod.schema as NonNullable<MountedRoute['schema']> }),\n });\n }\n } else routes = input;\n const schemas: Record<string, JSONSchema> = {\n ...(record(options.components?.schemas) as Record<string, JSONSchema> | undefined),\n };\n const doc: OpenAPIDocument = {\n openapi: '3.1.0',\n info: options.info ?? { title: 'EFC API', version: '1.0.0' },\n paths: {},\n components: { ...options.components, schemas },\n ...(options.servers && { servers: options.servers }),\n };\n const prefix = (options.basePath ?? '/v1/api').replace(/\\/+$/, '');\n const ids = new Set<string>();\n const pathShapes = new Map<string, string>();\n let sequence = 0;\n const convert = async (validator: Validator, label: string) => {\n const standard = (\n validator as {\n '~standard'?: { jsonSchema?: { input?: (options: { target: string }) => unknown } };\n }\n )['~standard'];\n let converted: unknown;\n try {\n if (standard?.jsonSchema?.input)\n converted = await standard.jsonSchema.input({ target: 'draft-2020-12' });\n else if (options.schemaToJSONSchema) converted = await options.schemaToJSONSchema(validator);\n else throw new Error('validator needs Standard JSON Schema support or schemaToJSONSchema');\n } catch (error) {\n throw new Error(`[EFC] OpenAPI ${label}: ${(error as Error).message}`, { cause: error });\n }\n if (typeof converted !== 'boolean' && !record(converted))\n throw new Error(`[EFC] OpenAPI ${label}: invalid JSON Schema`);\n let name: string;\n do {\n name = 'EfcRequest' + ++sequence;\n } while (Object.hasOwn(schemas, name));\n const ref = '#/components/schemas/' + pointer(name);\n schemas[name] = rebase(converted, ref) as JSONSchema;\n return { ref, schema: converted as JSONSchema };\n };\n for (const route of routes) {\n const paths = variants(prefix + (route.urlPath === '/' ? '' : route.urlPath));\n for (const method of route.methods) {\n const meta = route.meta?.[method];\n const explicit = meta?.openapi ?? {};\n if (explicit.hidden) continue;\n const request = schemaFor(route.schema, method);\n const roots: Partial<\n Record<'params' | 'query' | 'body', Awaited<ReturnType<typeof convert>>>\n > = {};\n for (const location of ['params', 'query', 'body'] as const) {\n if (request?.[location])\n roots[location] = await convert(\n request[location]!,\n `${method} ${route.urlPath} ${location}`,\n );\n }\n for (const [index, path] of paths.entries()) {\n const shape = path.replace(/\\{[^}]+\\}/g, '{}');\n const previous = pathShapes.get(shape);\n if (previous && previous !== path)\n throw new Error(`[EFC] OpenAPI: ambiguous paths ${previous} and ${path}`);\n pathShapes.set(shape, path);\n const item = (doc.paths[path] ??= {});\n if (Object.hasOwn(item, method.toLowerCase())) continue; // Router precedence: first handler wins.\n const pathNames = [...path.matchAll(/\\{([^}]+)\\}/g)].map((match) => match[1]!);\n const parameters: Record<string, unknown>[] = [];\n for (const location of ['params', 'query'] as const) {\n if (explicit.parameters !== undefined) break;\n const root = roots[location];\n let fields: ParameterShape;\n try {\n fields = parameterObject(root?.schema, root?.ref ?? '');\n } catch (error) {\n throw new Error(\n `[EFC] OpenAPI ${method} ${route.urlPath} ${location}: ${(error as Error).message}`,\n { cause: error },\n );\n }\n const { properties, required } = fields;\n const names =\n location === 'params'\n ? pathNames\n : [...new Set([...properties.keys(), ...Object.keys(meta?.request?.query ?? {})])];\n for (const name of names) {\n const field = properties.get(name);\n parameters.push({\n // Brackets keep one-element arrays as arrays in Express's query parser.\n name: location === 'query' && field?.array ? name + '[]' : name,\n in: location === 'params' ? 'path' : 'query',\n required: location === 'params' || required.has(name),\n schema: field?.schema ?? { type: 'string' },\n ...(location === 'query' && field?.object && { style: 'deepObject', explode: true }),\n ...(location === 'query' && field?.array && { style: 'form', explode: true }),\n ...(meta?.request?.[location]?.[name] !== undefined && {\n example: meta.request[location]![name],\n }),\n });\n }\n }\n for (const [name, example] of Object.entries(meta?.request?.headers ?? {})) {\n parameters.push({ name, in: 'header', schema: { type: 'string' }, example });\n }\n const requestedId =\n typeof explicit.operationId === 'string' ? explicit.operationId : meta?.operationId;\n const baseId =\n (requestedId ?? `${method.toLowerCase()}_${path.replace(/[^a-zA-Z0-9_]/g, '_')}`) +\n (requestedId && paths.length > 1 ? '_' + index : '');\n let id = baseId;\n if (requestedId && ids.has(id))\n throw new Error(`[EFC] OpenAPI: duplicate operationId ${id}`);\n let suffix = 2;\n while (ids.has(id)) id = baseId + '_' + suffix++;\n ids.add(id);\n const status = String(meta?.response?.status ?? 200);\n const response = {\n description: 'Response',\n ...(meta?.response?.body !== undefined && {\n content: { 'application/json': { example: meta.response.body } },\n }),\n };\n const overrides = { ...explicit };\n delete overrides.hidden;\n delete overrides.operationId;\n item[method.toLowerCase()] = {\n operationId: id,\n ...(meta?.description && { description: meta.description }),\n ...(meta?.summary && { summary: meta.summary }),\n ...(meta?.tags && { tags: meta.tags }),\n ...(parameters.length && { parameters }),\n ...(roots.query && { 'x-efc-query-schema': { $ref: roots.query.ref } }),\n ...((roots.body || meta?.request?.body !== undefined) && {\n requestBody: {\n required: roots.body ? acceptsEmptyObject(roots.body.schema) !== true : false,\n content: {\n 'application/json': {\n ...(roots.body && { schema: { $ref: roots.body.ref } }),\n ...(meta?.request?.body !== undefined && { example: meta.request.body }),\n },\n },\n },\n }),\n responses: {\n [status]: response,\n ...(request &&\n status !== '400' && { '400': { description: 'Request validation failed' } }),\n },\n ...(route.urlPath.includes('*') && { 'x-efc-catch-all': true }),\n ...overrides,\n };\n }\n }\n }\n return doc;\n}\n\nexport async function mountOpenAPI(\n app: Express,\n routes: MountedRoute[],\n options: OpenAPIOptions & { basePath?: string },\n) {\n const path = options.path ?? '/openapi.json';\n if (!path.startsWith('/') || /[?*:[\\](){}#]/.test(path))\n throw new Error('[EFC] openapi.path must be an absolute static URL path');\n // Probe the actual Express matchers before filtering hidden operations. This\n // also respects case/trailing-slash rules, dynamic routes and implicit HEAD.\n const conflict = await new Promise<boolean>((resolve, reject) => {\n const probe = Router();\n const api = Router();\n for (const route of routes) {\n if (route.methods.some((method) => method === 'GET' || method === 'HEAD'))\n api.get(route.pattern ?? route.urlPath, (_req, _res) => resolve(true));\n }\n probe.use(options.basePath ?? '/v1/api', api);\n probe({ method: 'GET', url: path } as Request, {} as Response, (error?: unknown) => {\n if (error) reject(error);\n else resolve(false);\n });\n });\n if (conflict) throw new Error(`[EFC] OpenAPI URL conflicts with a GET/HEAD route: ${path}`);\n const document = await generateOpenAPI(routes, options);\n app.get(path, (req, res, next) => {\n if (req.headers.upgrade) return next();\n res.json(document);\n });\n return document;\n}\n","import { asyncWrap, asyncErrorWrap } from './middleware.js';\nimport express from 'express';\nimport cors from 'cors';\nimport cookieParser from 'cookie-parser';\nimport type { EFCConfig } from './types.js';\nimport { runWithContext } from './context.js';\nimport { requestLogger, getLogger } from './logger.js';\nimport { httpTracing, traceHttpError } from './tracing.js';\nimport { isHttpError } from './errors.js';\n\n/** Shared production/test HTTP middleware stack; service boot remains in ignite(). */\nexport function createHttpApp(config: EFCConfig): express.Express {\n const globalMiddlewares = config.globalMiddlewares ?? [];\n const app = express();\n if (config.trustProxy !== undefined) app.set('trust proxy', config.trustProxy);\n // defineTable returns `bigint` for bigint columns and bigserial ids, which JSON.stringify\n // rejects; send them as strings (exact — a JS number would lose precision past 2^53).\n app.set('json replacer', (_key: string, value: unknown) =>\n typeof value === 'bigint' ? value.toString() : value,\n );\n\n // Wraps every request in its own AsyncLocalStorage context, first thing, so\n // requireAuth (below) and any downstream code — including a `$currentUser`\n // default resolved inside a mongoose `.create()` call — share the same store.\n app.use((_req, _res, next) => {\n runWithContext({}, next);\n });\n if (config.tracing && (config.tracing === true || config.tracing.http !== false))\n app.use(httpTracing());\n app.use(requestLogger());\n\n if (config.requestTimeout) {\n const ms = config.requestTimeout;\n app.use((_req, res, next) => {\n const timer = setTimeout(() => {\n if (!res.headersSent) res.status(408).json({ error: 'Request Timeout', statusCode: 408 });\n }, ms);\n const clear = () => clearTimeout(timer);\n res.once('finish', clear);\n res.once('close', clear);\n next();\n });\n }\n\n const corsOption = config.cors ?? true;\n if (corsOption !== false) {\n const origin =\n typeof corsOption === 'object' && corsOption.origin !== undefined ? corsOption.origin : true;\n const corsOpts = typeof corsOption === 'object' ? { ...corsOption, origin } : { origin };\n app.use(cors(corsOpts));\n }\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n app.use(cookieParser());\n\n for (const mw of globalMiddlewares) {\n app.use(asyncWrap(mw));\n }\n\n return app;\n}\n\nexport function mountErrorHandler(\n app: express.Express,\n onError?: express.ErrorRequestHandler,\n): void {\n app.use(traceHttpError);\n if (onError) {\n app.use(asyncErrorWrap(onError));\n }\n app.use(\n (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {\n // e.g. a handler that kept going after requestTimeout already answered 408.\n if (res.headersSent) {\n getLogger().warn({ err }, 'Error after the response was sent');\n if (!res.writableEnded) res.destroy();\n return;\n }\n // isHttpError() covers the common case, but errors can also arrive as plain\n // objects with a numeric statusCode (e.g. thrown across a module boundary, or\n // duck-typed by user code) — fall back to that shape before giving up to 500.\n // Only 4xx: a library's 5xx message can describe internals (hosts, SQL, paths).\n const status = (err as { statusCode?: unknown } | null)?.statusCode;\n const duckTyped =\n err instanceof Error && typeof status === 'number' && status >= 400 && status < 500\n ? (err as Error & { statusCode: number })\n : null;\n\n if (isHttpError(err)) {\n // ModelValidationError carries per-field issues; surface them like route validation does.\n const issues = (err as { issues?: unknown }).issues;\n res.status(err.statusCode).json({\n error: err.message,\n statusCode: err.statusCode,\n ...(issues !== undefined && { issues }),\n });\n } else if (duckTyped) {\n res\n .status(duckTyped.statusCode)\n .json({ error: duckTyped.message, statusCode: duckTyped.statusCode });\n } else {\n getLogger().error({ err }, 'Unhandled error');\n res.status(500).json({ error: 'Internal Server Error', statusCode: 500 });\n }\n },\n );\n}\n"]}
@@ -1,13 +1,17 @@
1
1
  import {
2
2
  runInThread
3
- } from "./chunk-3SWI46YK.js";
3
+ } from "./chunk-PUM5ZDAH.js";
4
4
  import {
5
5
  setEnqueueImpl,
6
6
  taskRegistry
7
- } from "./chunk-B6MB6HEG.js";
7
+ } from "./chunk-ZBQUYFI3.js";
8
8
  import {
9
9
  getLogger
10
- } from "./chunk-2IDRC7RK.js";
10
+ } from "./chunk-UJ2ISRLP.js";
11
+ import {
12
+ bullMQTelemetry,
13
+ taskContext
14
+ } from "./chunk-546TNO2V.js";
11
15
 
12
16
  // src/tasks/bullmq-backend.ts
13
17
  var closeImpl = null;
@@ -32,7 +36,7 @@ async function syncSchedules(queue) {
32
36
  pattern: def.options.schedule,
33
37
  ...def.options.timezone !== void 0 && { tz: def.options.timezone }
34
38
  },
35
- { name: def.name, data: {}, opts: jobOptions(def) }
39
+ { name: def.name, data: {}, opts: { ...jobOptions(def), telemetry: { omitContext: true } } }
36
40
  );
37
41
  }
38
42
  for (const s of await queue.getJobSchedulers(0, -1)) {
@@ -55,25 +59,23 @@ async function initBullMQ(opts) {
55
59
  throw new Error("[EFC] bullmq is not installed. Run: npm install bullmq");
56
60
  }
57
61
  const connection = parseRedisUrl(opts.redisUrl);
62
+ const telemetry = opts.tracing ? bullMQTelemetry() : void 0;
58
63
  const queue = new bullmq.Queue(opts.queue, {
64
+ ...telemetry && { telemetry },
59
65
  connection: { ...connection, enableOfflineQueue: false }
60
66
  });
61
67
  queue.on("error", () => {
62
68
  });
63
69
  const worker = new bullmq.Worker(
64
70
  opts.queue,
65
- async (job) => {
71
+ async (job) => taskContext(async () => {
66
72
  const def = taskRegistry.get(job.name);
67
- if (!def) {
68
- throw new Error(`[EFC] No task registered for name: ${job.name}`);
69
- }
70
- if (def.options.thread && def.filePath) {
71
- await runInThread(def.filePath, job.data);
72
- } else {
73
- await def.handler(job.data);
74
- }
75
- },
76
- { connection, concurrency: opts.concurrency }
73
+ if (!def) throw new Error(`[EFC] No task registered for name: ${job.name}`);
74
+ if (def.options.thread && def.filePath)
75
+ await runInThread(def.filePath, job.data, !!opts.tracing);
76
+ else await def.handler(job.data);
77
+ }, !!opts.tracing),
78
+ { connection, concurrency: opts.concurrency, ...telemetry && { telemetry } }
77
79
  );
78
80
  worker.on("failed", (job, err) => {
79
81
  getLogger().error(
@@ -94,17 +96,20 @@ async function initBullMQ(opts) {
94
96
  `[EFC] Cannot enqueue unknown task: "${name}". Is the task file in tasksDir?`
95
97
  );
96
98
  }
97
- const add = queue.waitUntilReady().then(() => queue.add(name, payload, jobOptions(def)));
99
+ let expired = false;
100
+ const deadline = new Error(
101
+ `[EFC] Cannot enqueue task "${name}": Redis at ${connection.host}:${connection.port} did not respond within ${opts.enqueueTimeout}ms`
102
+ );
103
+ const add = queue.waitUntilReady().then(() => {
104
+ if (expired) throw deadline;
105
+ return queue.add(name, payload, jobOptions(def));
106
+ });
98
107
  let timer;
99
108
  const timeout = new Promise((_, reject) => {
100
- timer = setTimeout(
101
- () => reject(
102
- new Error(
103
- `[EFC] Cannot enqueue task "${name}": Redis at ${connection.host}:${connection.port} did not respond within ${opts.enqueueTimeout}ms`
104
- )
105
- ),
106
- opts.enqueueTimeout
107
- );
109
+ timer = setTimeout(() => {
110
+ expired = true;
111
+ reject(deadline);
112
+ }, opts.enqueueTimeout);
108
113
  });
109
114
  try {
110
115
  await Promise.race([add, timeout]);
@@ -151,4 +156,4 @@ export {
151
156
  initBullMQ,
152
157
  parseRedisUrl
153
158
  };
154
- //# sourceMappingURL=chunk-OM2XJJWX.js.map
159
+ //# sourceMappingURL=chunk-EBJELA7T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tasks/bullmq-backend.ts"],"sourcesContent":["import { bullMQTelemetry, taskContext } from '../tracing.js';\nimport type { Job } from 'bullmq';\nimport type * as BullMQNS from 'bullmq';\nimport { taskRegistry, setEnqueueImpl } from './index.js';\nimport type { TaskDefinition } from '../types.js';\nimport { runInThread } from './thread-runner.js';\nimport { getLogger } from '../logger.js';\n\ninterface BullMQOpts {\n tracing?: boolean;\n redisUrl: string;\n concurrency: number;\n enqueueTimeout: number;\n queue: string;\n}\n\nlet closeImpl: (() => Promise<void>) | null = null;\nlet schedulesSynced: Promise<void> = Promise.resolve();\n\n/** Resolves once cron schedulers have been reconciled with the registry (tests, CLI). */\nexport function whenSchedulesSynced(): Promise<void> {\n return schedulesSynced;\n}\n\nexport const SCHEDULER_PREFIX = 'efc-cron:';\n\nfunction jobOptions(def: TaskDefinition) {\n return {\n // BullMQ's `attempts` counts the first run; `retries` counts only the re-runs.\n attempts: (def.options.retries ?? 3) + 1,\n backoff: { type: def.options.backoff ?? 'exponential', delay: 1000 },\n };\n}\n\n// One job scheduler per task with a `schedule`, keyed by task name. upsert is\n// idempotent, so every cluster worker can run this without creating duplicates;\n// schedulers whose task lost its `schedule` (or was deleted) are removed.\nasync function syncSchedules(queue: BullMQNS.Queue): Promise<void> {\n const wanted = new Set<string>();\n for (const def of taskRegistry.values()) {\n if (!def.options.schedule) continue;\n const id = SCHEDULER_PREFIX + def.name;\n wanted.add(id);\n await queue.upsertJobScheduler(\n id,\n {\n pattern: def.options.schedule,\n ...(def.options.timezone !== undefined && { tz: def.options.timezone }),\n },\n { name: def.name, data: {}, opts: { ...jobOptions(def), telemetry: { omitContext: true } } },\n );\n }\n for (const s of await queue.getJobSchedulers(0, -1)) {\n if (s.key.startsWith(SCHEDULER_PREFIX) && !wanted.has(s.key)) {\n await queue.removeJobScheduler(s.key);\n }\n }\n if (wanted.size > 0) getLogger().info(`Scheduled ${wanted.size} cron task(s)`);\n}\n\n/** Drains the BullMQ worker and closes both Redis connections. No-op if never initialised. */\nexport async function closeBullMQ(): Promise<void> {\n const close = closeImpl;\n closeImpl = null;\n await close?.();\n}\n\nexport async function initBullMQ(opts: BullMQOpts): Promise<void> {\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\n const connection = parseRedisUrl(opts.redisUrl);\n // With the offline queue on (ioredis default) queue.add() buffers forever while Redis is\n // down, so enqueue() never settles. Off, commands reject once the connection drops; the\n // initial connect is bounded by the enqueueTimeout race below.\n const telemetry = opts.tracing ? bullMQTelemetry() : undefined;\n const queue = new bullmq.Queue(opts.queue, {\n ...(telemetry && { telemetry }),\n connection: { ...connection, enableOfflineQueue: false },\n });\n // Without a listener, ioredis connection errors surface as unhandled 'error' events.\n queue.on('error', () => {});\n\n const worker = new bullmq.Worker(\n opts.queue,\n async (job: Job) =>\n taskContext(async () => {\n const def = taskRegistry.get(job.name);\n if (!def) throw new Error(`[EFC] No task registered for name: ${job.name}`);\n if (def.options.thread && def.filePath)\n await runInThread(def.filePath, job.data, !!opts.tracing);\n else await def.handler(job.data);\n }, !!opts.tracing),\n { connection, concurrency: opts.concurrency, ...(telemetry && { telemetry }) },\n );\n\n worker.on('failed', (job: Job | undefined, err: Error) => {\n getLogger().error(\n { task: job?.name, jobId: job?.id, attempt: job?.attemptsMade, err },\n `Task ${job?.name ?? 'unknown'} failed`,\n );\n });\n\n worker.on('error', (err: Error) => {\n getLogger().error(`Task worker error: ${err.message}`);\n });\n\n worker.on('completed', (job: Job) => {\n getLogger().info({ task: job.name, jobId: job.id }, `Task ${job.name} completed`);\n });\n\n setEnqueueImpl(async (name, payload) => {\n const def = taskRegistry.get(name);\n if (!def) {\n throw new Error(\n `[EFC] Cannot enqueue unknown task: \"${name}\". Is the task file in tasksDir?`,\n );\n }\n\n let expired = false;\n const deadline = new Error(\n `[EFC] Cannot enqueue task \"${name}\": Redis at ${connection.host}:${connection.port} did not respond within ${opts.enqueueTimeout}ms`,\n );\n const add = queue.waitUntilReady().then(() => {\n if (expired) throw deadline;\n return queue.add(name, payload, jobOptions(def));\n });\n\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n expired = true;\n reject(deadline);\n }, opts.enqueueTimeout);\n });\n\n try {\n await Promise.race([add, timeout]);\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('[EFC]')) throw err;\n throw new Error(\n `[EFC] Cannot enqueue task \"${name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n } finally {\n clearTimeout(timer);\n }\n });\n\n let closing = false;\n // Not awaited: a Redis outage at boot must not block the HTTP server from starting.\n schedulesSynced = queue\n .waitUntilReady()\n .then(() => syncSchedules(queue))\n .catch((err: unknown) => {\n // Shutting down before Redis ever answered aborts the wait — not a real failure.\n if (!closing) getLogger().error({ err }, 'Failed to sync cron task schedules');\n });\n\n closeImpl = async () => {\n closing = true;\n await worker.close();\n await queue.close();\n };\n\n getLogger().info('BullMQ backend initialised');\n}\n\ninterface RedisConnection {\n host: string;\n port: number;\n username?: string;\n password?: string;\n db?: number;\n tls?: Record<string, never>;\n}\n\nexport function parseRedisUrl(url: string): RedisConnection {\n try {\n const u = new URL(url);\n const result: RedisConnection = {\n host: u.hostname || 'localhost',\n port: parseInt(u.port || '6379', 10),\n };\n if (u.username) result.username = decodeURIComponent(u.username);\n if (u.password) result.password = decodeURIComponent(u.password);\n const db = parseInt(u.pathname.slice(1), 10);\n if (!Number.isNaN(db)) result.db = db;\n if (u.protocol === 'rediss:') result.tls = {};\n return result;\n } catch {\n return { host: 'localhost', port: 6379 };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,IAAI,YAA0C;AAC9C,IAAI,kBAAiC,QAAQ,QAAQ;AAO9C,IAAM,mBAAmB;AAEhC,SAAS,WAAW,KAAqB;AACvC,SAAO;AAAA;AAAA,IAEL,WAAW,IAAI,QAAQ,WAAW,KAAK;AAAA,IACvC,SAAS,EAAE,MAAM,IAAI,QAAQ,WAAW,eAAe,OAAO,IAAK;AAAA,EACrE;AACF;AAKA,eAAe,cAAc,OAAsC;AACjE,QAAM,SAAS,oBAAI,IAAY;AAC/B,aAAW,OAAO,aAAa,OAAO,GAAG;AACvC,QAAI,CAAC,IAAI,QAAQ,SAAU;AAC3B,UAAM,KAAK,mBAAmB,IAAI;AAClC,WAAO,IAAI,EAAE;AACb,UAAM,MAAM;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAS,IAAI,QAAQ;AAAA,QACrB,GAAI,IAAI,QAAQ,aAAa,UAAa,EAAE,IAAI,IAAI,QAAQ,SAAS;AAAA,MACvE;AAAA,MACA,EAAE,MAAM,IAAI,MAAM,MAAM,CAAC,GAAG,MAAM,EAAE,GAAG,WAAW,GAAG,GAAG,WAAW,EAAE,aAAa,KAAK,EAAE,EAAE;AAAA,IAC7F;AAAA,EACF;AACA,aAAW,KAAK,MAAM,MAAM,iBAAiB,GAAG,EAAE,GAAG;AACnD,QAAI,EAAE,IAAI,WAAW,gBAAgB,KAAK,CAAC,OAAO,IAAI,EAAE,GAAG,GAAG;AAC5D,YAAM,MAAM,mBAAmB,EAAE,GAAG;AAAA,IACtC;AAAA,EACF;AACA,MAAI,OAAO,OAAO,EAAG,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