express-file-cluster 0.9.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/dist/auth/index.cjs +6 -7
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +7 -2
  4. package/dist/auth/index.d.ts +7 -2
  5. package/dist/auth/index.js +5 -6
  6. package/dist/{chunk-QL6EWT4B.cjs → chunk-4DOHQU6I.cjs} +9 -7
  7. package/dist/chunk-4DOHQU6I.cjs.map +1 -0
  8. package/dist/chunk-73XJUT2S.js +366 -0
  9. package/dist/chunk-73XJUT2S.js.map +1 -0
  10. package/dist/{chunk-ATL4GYFU.js → chunk-7KC2H76D.js} +50 -8
  11. package/dist/chunk-7KC2H76D.js.map +1 -0
  12. package/dist/{chunk-TYR2GZZE.cjs → chunk-7KO4DJRJ.cjs} +19 -14
  13. package/dist/chunk-7KO4DJRJ.cjs.map +1 -0
  14. package/dist/{chunk-UBQYQPBU.js → chunk-ATVD2HGC.js} +4 -4
  15. package/dist/{chunk-R34R7QPD.cjs → chunk-DCJOWFVD.cjs} +3 -3
  16. package/dist/{chunk-R34R7QPD.cjs.map → chunk-DCJOWFVD.cjs.map} +1 -1
  17. package/dist/chunk-DUADUR6R.cjs +366 -0
  18. package/dist/chunk-DUADUR6R.cjs.map +1 -0
  19. package/dist/{chunk-BBSZLGZW.js → chunk-EGSSZUVO.js} +8 -6
  20. package/dist/chunk-EGSSZUVO.js.map +1 -0
  21. package/dist/{chunk-TI24L4XE.cjs → chunk-GBI77W5T.cjs} +6 -2
  22. package/dist/chunk-GBI77W5T.cjs.map +1 -0
  23. package/dist/{chunk-RTF7PHS2.cjs → chunk-HBCY7ILD.cjs} +306 -119
  24. package/dist/chunk-HBCY7ILD.cjs.map +1 -0
  25. package/dist/{chunk-ANUSWEAP.cjs → chunk-KFVFP2Q7.cjs} +59 -17
  26. package/dist/chunk-KFVFP2Q7.cjs.map +1 -0
  27. package/dist/{chunk-RS4MXCPW.js → chunk-NI2BNGGV.js} +2 -2
  28. package/dist/{chunk-X2US4RAM.cjs → chunk-NKLOE4AK.cjs} +11 -13
  29. package/dist/chunk-NKLOE4AK.cjs.map +1 -0
  30. package/dist/{chunk-RRQ2RK5M.js → chunk-PGJQK36V.js} +195 -8
  31. package/dist/chunk-PGJQK36V.js.map +1 -0
  32. package/dist/{chunk-QKQZF573.js → chunk-QDEDOHP7.js} +4 -6
  33. package/dist/chunk-QDEDOHP7.js.map +1 -0
  34. package/dist/{chunk-UTM4PEVG.js → chunk-R4XO4SVM.js} +10 -5
  35. package/dist/chunk-R4XO4SVM.js.map +1 -0
  36. package/dist/chunk-R52CUEGT.js +74 -0
  37. package/dist/chunk-R52CUEGT.js.map +1 -0
  38. package/dist/{chunk-HBYSKULC.js → chunk-RAB44UGX.js} +5 -1
  39. package/dist/chunk-RAB44UGX.js.map +1 -0
  40. package/dist/{chunk-7YEX4MQV.cjs → chunk-WBLUGOAG.cjs} +42 -6
  41. package/dist/chunk-WBLUGOAG.cjs.map +1 -0
  42. package/dist/{chunk-T4OHFU5T.cjs → chunk-YK4ZM3CA.cjs} +15 -15
  43. package/dist/{chunk-T4OHFU5T.cjs.map → chunk-YK4ZM3CA.cjs.map} +1 -1
  44. package/dist/cli/db-runner.cjs +2012 -120
  45. package/dist/cli/db-runner.cjs.map +1 -1
  46. package/dist/cli/db-runner.js +1989 -97
  47. package/dist/cli/db-runner.js.map +1 -1
  48. package/dist/cli/index.cjs +101 -43
  49. package/dist/cli/index.cjs.map +1 -1
  50. package/dist/cli/index.js +80 -22
  51. package/dist/cli/index.js.map +1 -1
  52. package/dist/docs/api-reference/auth.md +10 -8
  53. package/dist/docs/api-reference/collection.md +44 -1
  54. package/dist/docs/api-reference/ignite.md +22 -3
  55. package/dist/docs/api-reference/types.md +99 -0
  56. package/dist/docs/cli/add.md +1 -1
  57. package/dist/docs/cli/db.md +2 -2
  58. package/dist/docs/contributing/index.md +1 -1
  59. package/dist/docs/core-concepts/background-tasks.md +6 -3
  60. package/dist/docs/getting-started/index.md +3 -2
  61. package/dist/docs/guides/authentication.md +34 -24
  62. package/dist/docs/guides/caching.md +32 -1
  63. package/dist/docs/guides/database.md +14 -0
  64. package/dist/docs/guides/feature-matrix.md +58 -0
  65. package/dist/docs/guides/migrations.md +23 -2
  66. package/dist/docs/guides/oauth.md +15 -1
  67. package/dist/docs/guides/which-api.md +2 -2
  68. package/dist/docs/index.md +4 -1
  69. package/dist/docs/skills/SKILL.md +2 -2
  70. package/dist/docs/skills/api-surface.md +10 -4
  71. package/dist/docs/skills/auth-internals.md +3 -3
  72. package/dist/docs/skills/tasks-internals.md +4 -3
  73. package/dist/docs/skills/what-not-to-invent.md +4 -3
  74. package/dist/docs/versioning.md +42 -0
  75. package/dist/index.cjs +144 -51
  76. package/dist/index.cjs.map +1 -1
  77. package/dist/index.d.cts +204 -3
  78. package/dist/index.d.ts +204 -3
  79. package/dist/index.js +107 -14
  80. package/dist/index.js.map +1 -1
  81. package/dist/pgboss-backend-FW42SBSM.js +14 -0
  82. package/dist/pgboss-backend-RVHUBJTU.cjs +14 -0
  83. package/dist/{pgboss-backend-TCHI7CHM.cjs.map → pgboss-backend-RVHUBJTU.cjs.map} +1 -1
  84. package/dist/registry/index.json +34 -3
  85. package/dist/registry/js-mongo/account-security.json +1 -1
  86. package/dist/registry/js-mongo/admin-users.json +1 -1
  87. package/dist/registry/js-mongo/auth.json +1 -1
  88. package/dist/registry/js-mongo/auth@apple.json +1 -1
  89. package/dist/registry/js-mongo/auth@google.json +1 -1
  90. package/dist/registry/js-mongo/email-verification.json +1 -1
  91. package/dist/registry/js-mongo/forgot-password.json +1 -1
  92. package/dist/registry/js-mongo/user-profile.json +1 -1
  93. package/dist/registry/js-mongo-collection/_base.json +1 -0
  94. package/dist/registry/js-mongo-collection/account-security.json +1 -0
  95. package/dist/registry/js-mongo-collection/account-settings.json +1 -0
  96. package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
  97. package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
  98. package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
  99. package/dist/registry/js-mongo-collection/admin-content.json +1 -0
  100. package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
  101. package/dist/registry/js-mongo-collection/admin-support.json +1 -0
  102. package/dist/registry/js-mongo-collection/admin-system.json +1 -0
  103. package/dist/registry/js-mongo-collection/admin-users.json +1 -0
  104. package/dist/registry/js-mongo-collection/admin.json +1 -0
  105. package/dist/registry/js-mongo-collection/auth.json +1 -0
  106. package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
  107. package/dist/registry/js-mongo-collection/auth@google.json +1 -0
  108. package/dist/registry/js-mongo-collection/billing.json +1 -0
  109. package/dist/registry/js-mongo-collection/email-client.json +1 -0
  110. package/dist/registry/js-mongo-collection/email-verification.json +1 -0
  111. package/dist/registry/js-mongo-collection/files.json +1 -0
  112. package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
  113. package/dist/registry/js-mongo-collection/notifications.json +1 -0
  114. package/dist/registry/js-mongo-collection/support.json +1 -0
  115. package/dist/registry/js-mongo-collection/user-profile.json +1 -0
  116. package/dist/registry/js-pg-model/account-security.json +1 -1
  117. package/dist/registry/js-pg-model/admin-users.json +1 -1
  118. package/dist/registry/js-pg-model/auth.json +1 -1
  119. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  120. package/dist/registry/js-pg-model/auth@google.json +1 -1
  121. package/dist/registry/js-pg-model/email-verification.json +1 -1
  122. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  123. package/dist/registry/js-pg-model/user-profile.json +1 -1
  124. package/dist/registry/js-pg-table/account-security.json +1 -1
  125. package/dist/registry/js-pg-table/admin-users.json +1 -1
  126. package/dist/registry/js-pg-table/auth.json +1 -1
  127. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  128. package/dist/registry/js-pg-table/auth@google.json +1 -1
  129. package/dist/registry/js-pg-table/email-verification.json +1 -1
  130. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  131. package/dist/registry/js-pg-table/user-profile.json +1 -1
  132. package/dist/registry/ts-mongo/account-security.json +1 -1
  133. package/dist/registry/ts-mongo/admin-users.json +1 -1
  134. package/dist/registry/ts-mongo/auth.json +1 -1
  135. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  136. package/dist/registry/ts-mongo/auth@google.json +1 -1
  137. package/dist/registry/ts-mongo/email-verification.json +1 -1
  138. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  139. package/dist/registry/ts-mongo/user-profile.json +1 -1
  140. package/dist/registry/ts-mongo-collection/_base.json +1 -0
  141. package/dist/registry/ts-mongo-collection/account-security.json +1 -0
  142. package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
  143. package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
  144. package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
  145. package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
  146. package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
  147. package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
  148. package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
  149. package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
  150. package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
  151. package/dist/registry/ts-mongo-collection/admin.json +1 -0
  152. package/dist/registry/ts-mongo-collection/auth.json +1 -0
  153. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
  154. package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
  155. package/dist/registry/ts-mongo-collection/billing.json +1 -0
  156. package/dist/registry/ts-mongo-collection/email-client.json +1 -0
  157. package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
  158. package/dist/registry/ts-mongo-collection/files.json +1 -0
  159. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
  160. package/dist/registry/ts-mongo-collection/notifications.json +1 -0
  161. package/dist/registry/ts-mongo-collection/support.json +1 -0
  162. package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
  163. package/dist/registry/ts-pg-model/account-security.json +1 -1
  164. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  165. package/dist/registry/ts-pg-model/auth.json +1 -1
  166. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  167. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  168. package/dist/registry/ts-pg-model/email-verification.json +1 -1
  169. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  170. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  171. package/dist/registry/ts-pg-table/account-security.json +1 -1
  172. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  173. package/dist/registry/ts-pg-table/auth.json +1 -1
  174. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  175. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  176. package/dist/registry/ts-pg-table/email-verification.json +1 -1
  177. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  178. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  179. package/dist/tasks/index.cjs +4 -2
  180. package/dist/tasks/index.cjs.map +1 -1
  181. package/dist/tasks/index.d.cts +4 -2
  182. package/dist/tasks/index.d.ts +4 -2
  183. package/dist/tasks/index.js +3 -1
  184. package/dist/thread-runner.cjs +8 -0
  185. package/dist/thread-runner.cjs.map +1 -0
  186. package/dist/thread-runner.d.cts +3 -0
  187. package/dist/thread-runner.d.ts +3 -0
  188. package/dist/thread-runner.js +8 -0
  189. package/dist/thread-runner.js.map +1 -0
  190. package/dist/{types-BY-ObnZH.d.ts → types-Bnxvj3l0.d.cts} +14 -2
  191. package/dist/{types-BY-ObnZH.d.cts → types-Bnxvj3l0.d.ts} +14 -2
  192. package/package.json +1 -1
  193. package/dist/chunk-277BSYVH.js +0 -127
  194. package/dist/chunk-277BSYVH.js.map +0 -1
  195. package/dist/chunk-7YEX4MQV.cjs.map +0 -1
  196. package/dist/chunk-ANUSWEAP.cjs.map +0 -1
  197. package/dist/chunk-ATL4GYFU.js.map +0 -1
  198. package/dist/chunk-BBSZLGZW.js.map +0 -1
  199. package/dist/chunk-HBYSKULC.js.map +0 -1
  200. package/dist/chunk-HXV543HZ.js +0 -177
  201. package/dist/chunk-HXV543HZ.js.map +0 -1
  202. package/dist/chunk-LJNSJFOL.js +0 -38
  203. package/dist/chunk-LJNSJFOL.js.map +0 -1
  204. package/dist/chunk-QKQZF573.js.map +0 -1
  205. package/dist/chunk-QL6EWT4B.cjs.map +0 -1
  206. package/dist/chunk-RRQ2RK5M.js.map +0 -1
  207. package/dist/chunk-RTF7PHS2.cjs.map +0 -1
  208. package/dist/chunk-TI24L4XE.cjs.map +0 -1
  209. package/dist/chunk-TYR2GZZE.cjs.map +0 -1
  210. package/dist/chunk-UTM4PEVG.js.map +0 -1
  211. package/dist/chunk-VQSWSYK6.cjs +0 -177
  212. package/dist/chunk-VQSWSYK6.cjs.map +0 -1
  213. package/dist/chunk-X2US4RAM.cjs.map +0 -1
  214. package/dist/chunk-YL37D6KM.cjs +0 -127
  215. package/dist/chunk-YL37D6KM.cjs.map +0 -1
  216. package/dist/pgboss-backend-QKBXVJ6B.js +0 -14
  217. package/dist/pgboss-backend-TCHI7CHM.cjs +0 -14
  218. /package/dist/{chunk-UBQYQPBU.js.map → chunk-ATVD2HGC.js.map} +0 -0
  219. /package/dist/{chunk-RS4MXCPW.js.map → chunk-NI2BNGGV.js.map} +0 -0
  220. /package/dist/{pgboss-backend-QKBXVJ6B.js.map → pgboss-backend-FW42SBSM.js.map} +0 -0
@@ -0,0 +1,366 @@
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; }// src/context.ts
2
+ var _async_hooks = require('async_hooks');
3
+ var storage = new (0, _async_hooks.AsyncLocalStorage)();
4
+ function runWithContext(ctx, fn) {
5
+ return storage.run(ctx, fn);
6
+ }
7
+ function getRequestContext() {
8
+ return storage.getStore();
9
+ }
10
+ function setCurrentUser(user) {
11
+ const store = storage.getStore();
12
+ if (store) store.user = user;
13
+ }
14
+ function getCurrentUser() {
15
+ return _optionalChain([storage, 'access', _ => _.getStore, 'call', _2 => _2(), 'optionalAccess', _3 => _3.user]);
16
+ }
17
+
18
+ // src/logger.ts
19
+ var _cluster = require('cluster'); var _cluster2 = _interopRequireDefault(_cluster);
20
+ var _crypto = require('crypto');
21
+ var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
22
+ var _pino = require('pino');
23
+ var LEVEL_LABELS = {
24
+ 10: _picocolors2.default.gray("TRACE"),
25
+ 20: _picocolors2.default.blue("DEBUG"),
26
+ 30: _picocolors2.default.green("INFO "),
27
+ 40: _picocolors2.default.yellow("WARN "),
28
+ 50: _picocolors2.default.red("ERROR"),
29
+ 60: _picocolors2.default.bgRed("FATAL")
30
+ };
31
+ var OMIT = /* @__PURE__ */ new Set(["level", "time", "msg", "pid", "hostname", "worker", "reqId"]);
32
+ function prettyStream(out = process.stdout) {
33
+ return {
34
+ write(line) {
35
+ let rec;
36
+ try {
37
+ rec = JSON.parse(line);
38
+ } catch (e2) {
39
+ out.write(line);
40
+ return;
41
+ }
42
+ const time = new Date(rec["time"]).toTimeString().slice(0, 8);
43
+ const level = _nullishCoalesce(LEVEL_LABELS[rec["level"]], () => ( String(rec["level"])));
44
+ const worker = rec["worker"] !== void 0 ? _picocolors2.default.dim(`[${String(rec["worker"])}] `) : "";
45
+ const reqId = rec["reqId"] ? _picocolors2.default.magenta(String(rec["reqId"]).slice(0, 8)) + " " : "";
46
+ const extra = Object.entries(rec).filter(([k]) => !OMIT.has(k));
47
+ const err = rec["err"];
48
+ const fields = extra.filter(([k]) => k !== "err").map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
49
+ out.write(
50
+ `${_picocolors2.default.dim(time)} ${level} ${worker}${reqId}${String(_nullishCoalesce(rec["msg"], () => ( "")))}` + (fields ? " " + _picocolors2.default.dim(fields) : "") + (_optionalChain([err, 'optionalAccess', _4 => _4.stack]) ? "\n" + _picocolors2.default.red(err.stack) : "") + "\n"
51
+ );
52
+ }
53
+ };
54
+ }
55
+ function workerLabel() {
56
+ return _cluster2.default.isWorker ? `w${_nullishCoalesce(_optionalChain([_cluster2.default, 'access', _5 => _5.worker, 'optionalAccess', _6 => _6.id]), () => ( "?"))}` : "primary";
57
+ }
58
+ function build(config2) {
59
+ if (config2 === false) return _pino.pino.call(void 0, { level: "silent" });
60
+ const opts = _nullishCoalesce(config2, () => ( {}));
61
+ const pretty = _nullishCoalesce(opts.pretty, () => ( (process.env["NODE_ENV"] !== "production" && process.stdout.isTTY === true)));
62
+ const base = { worker: workerLabel() };
63
+ const level = _nullishCoalesce(opts.level, () => ( "info"));
64
+ return pretty ? _pino.pino.call(void 0, { level, base, errorKey: "err" }, prettyStream()) : _pino.pino.call(void 0, { level, base, errorKey: "err", timestamp: _pino.pino.stdTimeFunctions.isoTime });
65
+ }
66
+ var rootLogger = build(void 0);
67
+ var logRequests = true;
68
+ function configureLogger(config2) {
69
+ rootLogger = build(config2);
70
+ logRequests = config2 !== false && (_nullishCoalesce(_optionalChain([config2, 'optionalAccess', _7 => _7.requests]), () => ( true)));
71
+ }
72
+ function getLogger() {
73
+ return _nullishCoalesce(_optionalChain([getRequestContext, 'call', _8 => _8(), 'optionalAccess', _9 => _9.log]), () => ( rootLogger));
74
+ }
75
+ var logger = new Proxy({}, {
76
+ get(_t, prop) {
77
+ const target = getLogger();
78
+ const value = target[prop];
79
+ return typeof value === "function" ? value.bind(target) : value;
80
+ }
81
+ });
82
+ var SAFE_REQUEST_ID = /^[\w.:-]{1,128}$/;
83
+ function requestLogger() {
84
+ return (req, res, next) => {
85
+ const incoming = req.get("x-request-id");
86
+ const id = incoming && SAFE_REQUEST_ID.test(incoming) ? incoming : _crypto.randomUUID.call(void 0, );
87
+ const log = rootLogger.child({ reqId: id });
88
+ req.id = id;
89
+ req.log = log;
90
+ res.setHeader("X-Request-Id", id);
91
+ const ctx = getRequestContext();
92
+ if (ctx) {
93
+ ctx.requestId = id;
94
+ ctx.log = log;
95
+ }
96
+ if (logRequests) {
97
+ const start = process.hrtime.bigint();
98
+ res.on("finish", () => {
99
+ const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
100
+ const status = res.statusCode;
101
+ const line = {
102
+ method: req.method,
103
+ url: req.originalUrl,
104
+ status,
105
+ durationMs: Math.round(durationMs * 10) / 10
106
+ };
107
+ const msg = `${req.method} ${req.originalUrl} ${status}`;
108
+ if (status >= 500) log.error(line, msg);
109
+ else if (status >= 400) log.warn(line, msg);
110
+ else log.info(line, msg);
111
+ });
112
+ }
113
+ next();
114
+ };
115
+ }
116
+
117
+ // src/db/query-log.ts
118
+
119
+ var DEFAULTS = { slowMs: 500, nPlusOne: 10 };
120
+ var config;
121
+ var listeners = /* @__PURE__ */ new Set();
122
+ var enableHooks = [];
123
+ function configureQueryLog(logging) {
124
+ const q = logging === false ? void 0 : _optionalChain([logging, 'optionalAccess', _10 => _10.queries]);
125
+ config = !q ? void 0 : q === true ? { all: true, ...DEFAULTS } : {
126
+ all: _nullishCoalesce(q.all, () => ( false)),
127
+ slowMs: _nullishCoalesce(q.slowMs, () => ( DEFAULTS.slowMs)),
128
+ nPlusOne: _nullishCoalesce(q.nPlusOne, () => ( DEFAULTS.nPlusOne))
129
+ };
130
+ if (config) for (const hook of enableHooks) hook();
131
+ }
132
+ function active() {
133
+ return config !== void 0 || listeners.size > 0;
134
+ }
135
+ function whenQueryTracking(install) {
136
+ enableHooks.push(install);
137
+ if (active()) install();
138
+ }
139
+ var frames = new (0, _async_hooks.AsyncLocalStorage)();
140
+ function countStatement() {
141
+ for (let f = frames.getStore(); f; f = f.parent) f.statements++;
142
+ }
143
+ function untracked(fn) {
144
+ return frames.run(void 0, fn);
145
+ }
146
+ function callSite(callee) {
147
+ const holder = {};
148
+ Error.captureStackTrace(holder, callee);
149
+ const line = _optionalChain([holder, 'access', _11 => _11.stack, 'optionalAccess', _12 => _12.split, 'call', _13 => _13("\n"), 'access', _14 => _14[1]]);
150
+ return _optionalChain([line, 'optionalAccess', _15 => _15.trim, 'call', _16 => _16(), 'access', _17 => _17.replace, 'call', _18 => _18(/^at /, "")]);
151
+ }
152
+ function emit(event, site, top) {
153
+ for (const listener of listeners) listener(event);
154
+ if (!config) return;
155
+ const log = getLogger();
156
+ const msg = `${event.model}.${event.op} ${event.durationMs}ms`;
157
+ const fields = { ...event };
158
+ delete fields.reqId;
159
+ if (event.durationMs >= config.slowMs) {
160
+ log.warn({ ...fields, slow: true }, `Slow query: ${msg}`);
161
+ } else if (config.all) {
162
+ log.info(fields, msg);
163
+ }
164
+ if (top && config.nPlusOne !== false) detectNPlusOne(event, site, config.nPlusOne);
165
+ }
166
+ function detectNPlusOne(event, site, threshold) {
167
+ const ctx = getRequestContext();
168
+ if (!ctx) return;
169
+ const key = `${event.model}.${event.op}`;
170
+ const counts = ctx.queryCounts ??= /* @__PURE__ */ new Map();
171
+ const n = (_nullishCoalesce(counts.get(key), () => ( 0))) + 1;
172
+ counts.set(key, n);
173
+ if (n !== threshold) return;
174
+ getLogger().warn(
175
+ { model: event.model, op: event.op, count: n, ...site !== void 0 && { site } },
176
+ `Possible N+1: ${key} ran ${n} times in one request \u2014 load them in one query instead`
177
+ );
178
+ }
179
+ function traceOps(model, target, ops) {
180
+ const t = target;
181
+ for (const op of ops) {
182
+ const fn = t[op];
183
+ const traced = function(...args) {
184
+ if (!active()) return fn.apply(this, args);
185
+ const parent = frames.getStore();
186
+ const frame = { statements: 0, parent };
187
+ const site = !parent && config && config.nPlusOne !== false ? callSite(traced) : void 0;
188
+ const start = process.hrtime.bigint();
189
+ const finish = (error) => {
190
+ const durationMs = Math.round(Number(process.hrtime.bigint() - start) / 1e5) / 10;
191
+ const reqId = _optionalChain([getRequestContext, 'call', _19 => _19(), 'optionalAccess', _20 => _20.requestId]);
192
+ emit(
193
+ {
194
+ model,
195
+ op,
196
+ durationMs,
197
+ statements: frame.statements,
198
+ ...reqId !== void 0 && { reqId },
199
+ ...error !== void 0 && { error: _nullishCoalesce(_optionalChain([error, 'optionalAccess', _21 => _21.message]), () => ( String(error))) }
200
+ },
201
+ site,
202
+ !parent
203
+ );
204
+ };
205
+ return frames.run(frame, () => fn.apply(this, args)).then(
206
+ (result) => {
207
+ finish();
208
+ return result;
209
+ },
210
+ (err) => {
211
+ finish(err);
212
+ throw err;
213
+ }
214
+ );
215
+ };
216
+ t[op] = traced;
217
+ }
218
+ return target;
219
+ }
220
+
221
+ // src/db/postgres.ts
222
+ var pool;
223
+ function notInstalled(err, pkg, install) {
224
+ const code = err.code;
225
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" ? new Error(`[EFC] ${pkg} is not installed. Run: ${install}`) : err;
226
+ }
227
+ var orm;
228
+ async function connectPostgres(url, poolConfig = {}) {
229
+ let PoolCtor;
230
+ try {
231
+ const pg = await Promise.resolve().then(() => _interopRequireWildcard(require("pg")));
232
+ PoolCtor = _nullishCoalesce(_optionalChain([pg, 'access', _22 => _22.default, 'optionalAccess', _23 => _23.Pool]), () => ( pg.Pool));
233
+ } catch (err) {
234
+ throw notInstalled(err, "pg", "npm install pg drizzle-orm");
235
+ }
236
+ let drizzle;
237
+ try {
238
+ ({ drizzle } = await Promise.resolve().then(() => _interopRequireWildcard(require("drizzle-orm/node-postgres"))));
239
+ } catch (err) {
240
+ throw notInstalled(err, "drizzle-orm", "npm install drizzle-orm");
241
+ }
242
+ const next = new PoolCtor({
243
+ connectionString: url,
244
+ ...poolConfig.max !== void 0 && { max: poolConfig.max },
245
+ ...poolConfig.idleTimeoutMs !== void 0 && { idleTimeoutMillis: poolConfig.idleTimeoutMs },
246
+ ...poolConfig.connectionTimeoutMs !== void 0 && {
247
+ connectionTimeoutMillis: poolConfig.connectionTimeoutMs
248
+ }
249
+ });
250
+ next.on("error", (err) => getLogger().error({ err }, "PostgreSQL pool error"));
251
+ try {
252
+ await next.query("select 1");
253
+ } catch (err) {
254
+ await next.end().catch(() => {
255
+ });
256
+ throw explainPostgresError(err, url);
257
+ }
258
+ pool = next;
259
+ orm = drizzle(next, { logger: { logQuery: countStatement } });
260
+ getLogger().info("PostgreSQL connected");
261
+ return next;
262
+ }
263
+ function describeUrl(url) {
264
+ try {
265
+ const u = new URL(url);
266
+ const database = decodeURIComponent(u.pathname.slice(1)) || "(default)";
267
+ return {
268
+ where: `${u.hostname || "localhost"}:${u.port || "5432"}`,
269
+ user: decodeURIComponent(u.username) || "(none)",
270
+ database
271
+ };
272
+ } catch (e3) {
273
+ return { where: "(unparsable DATABASE_URL)", user: "?", database: "?" };
274
+ }
275
+ }
276
+ function explainPostgresError(err, url) {
277
+ const e = err;
278
+ const msg = _nullishCoalesce(e.message, () => ( ""));
279
+ const { where, user, database } = describeUrl(url);
280
+ const hosted = "For Neon, Supabase or RDS, copy the full connection string from the dashboard.";
281
+ let text;
282
+ if (/client password must be a string/.test(msg)) {
283
+ text = `PostgreSQL asked for a password and DATABASE_URL has none (user "${user}" at ${where}). Put it in the URL: postgres://${user === "(none)" ? "user" : user}:<password>@${where}/${database === "(default)" ? "db" : database}. ${hosted}`;
284
+ } else if (e.code === "28P01") {
285
+ text = `PostgreSQL rejected the password for user "${user}" at ${where}. Check DATABASE_URL (special characters in the password must be URL-encoded). ${hosted}`;
286
+ } else if (e.code === "28000" && /role .* does not exist/.test(msg)) {
287
+ text = `PostgreSQL has no user "${user}" at ${where}. Create it (CREATE ROLE ${user} LOGIN PASSWORD '\u2026';) or fix the user in DATABASE_URL.`;
288
+ } else if (/no pg_hba\.conf entry.*no encryption/.test(msg)) {
289
+ text = `PostgreSQL at ${where} only accepts encrypted connections. Add ?sslmode=require to DATABASE_URL.`;
290
+ } else if (e.code === "28000") {
291
+ text = `PostgreSQL at ${where} refused user "${user}": ${msg}`;
292
+ } else if (e.code === "3D000") {
293
+ text = `Database "${database}" does not exist at ${where}. Create it first: createdb ${database} (or CREATE DATABASE "${database}";).`;
294
+ } else if (/does not support SSL/.test(msg)) {
295
+ text = `PostgreSQL at ${where} doesn't support SSL. Remove sslmode / ssl from DATABASE_URL (local servers usually run without it).`;
296
+ } else if (e.code === "ECONNREFUSED") {
297
+ text = `Nothing is accepting connections at ${where}. Is PostgreSQL running, and is the host/port in DATABASE_URL right?`;
298
+ } else if (e.code === "ENOTFOUND" || e.code === "EAI_AGAIN") {
299
+ text = `Can't resolve the PostgreSQL host in DATABASE_URL (${where}). Check the hostname.`;
300
+ } else if (e.code === "ETIMEDOUT" || /timeout/i.test(msg)) {
301
+ text = `Timed out connecting to PostgreSQL at ${where}. Check the host, and that a firewall / the provider's IP allow-list lets this machine in.`;
302
+ }
303
+ return text ? new Error(`[EFC] ${text}`, { cause: err }) : err;
304
+ }
305
+ async function checkConnectionBudget(perMachine, breakdown) {
306
+ const log = getLogger();
307
+ try {
308
+ const { rows } = await getPool().query(
309
+ `select current_setting('max_connections')::int as max,
310
+ current_setting('superuser_reserved_connections')::int as reserved`
311
+ );
312
+ const { max, reserved } = rows[0];
313
+ const usable = max - reserved;
314
+ if (perMachine > usable) {
315
+ log.warn(
316
+ `[EFC] PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}), but the server allows ${usable} (max_connections ${max} \u2212 ${reserved} reserved). Under load, queries will fail with "too many clients". Lower databasePool.max or workers, or put PgBouncer in front.`
317
+ );
318
+ } else {
319
+ log.info(
320
+ `PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}) of ${usable} allowed \u2014 multiply by your instance count if you run several`
321
+ );
322
+ }
323
+ } catch (e4) {
324
+ }
325
+ }
326
+ function getOrm() {
327
+ if (!orm) {
328
+ throw new Error(
329
+ "[EFC] PostgreSQL not connected \u2014 set database/databaseUrl in ignite() (or call connectPostgres)"
330
+ );
331
+ }
332
+ return orm;
333
+ }
334
+ function getPool() {
335
+ if (!pool) throw new Error("[EFC] PostgreSQL not connected");
336
+ return pool;
337
+ }
338
+ async function closePostgres() {
339
+ const p = pool;
340
+ pool = void 0;
341
+ orm = void 0;
342
+ await _optionalChain([p, 'optionalAccess', _24 => _24.end, 'call', _25 => _25()]);
343
+ }
344
+
345
+
346
+
347
+
348
+
349
+
350
+
351
+
352
+
353
+
354
+
355
+
356
+
357
+
358
+
359
+
360
+
361
+
362
+
363
+
364
+
365
+ exports.runWithContext = runWithContext; exports.setCurrentUser = setCurrentUser; exports.getCurrentUser = getCurrentUser; exports.configureLogger = configureLogger; exports.getLogger = getLogger; exports.logger = logger; exports.requestLogger = requestLogger; exports.configureQueryLog = configureQueryLog; exports.whenQueryTracking = whenQueryTracking; exports.countStatement = countStatement; exports.untracked = untracked; exports.traceOps = traceOps; exports.notInstalled = notInstalled; exports.connectPostgres = connectPostgres; exports.explainPostgresError = explainPostgresError; exports.checkConnectionBudget = checkConnectionBudget; exports.getOrm = getOrm; exports.getPool = getPool; exports.closePostgres = closePostgres;
366
+ //# sourceMappingURL=chunk-DUADUR6R.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-DUADUR6R.cjs","../src/context.ts","../src/logger.ts","../src/db/query-log.ts","../src/db/postgres.ts"],"names":[],"mappings":"AAAA;ACAA,0CAAkC;AAWlC,IAAM,QAAA,EAAU,IA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pE,EAAA;AACF;AAOuE;AAC3D,EAAA;AACe,EAAA;AACwB,EAAA;AAClC,EAAA;AACX,EAAA;AAC8C,EAAA;AACzC,IAAA;AACsB,EAAA;AACoC,IAAA;AACE,EAAA;AAChB,IAAA;AACQ,EAAA;AAC9B,IAAA;AACA,EAAA;AAC+B,IAAA;AAC/B,EAAA;AAC2B,IAAA;AACb,EAAA;AACd,IAAA;AACO,EAAA;AACe,IAAA;AACQ,EAAA;AACO,IAAA;AACT,EAAA;AACJ,IAAA;AACvD,EAAA;AAC4D,EAAA;AAC9D;AAUiB;AACO,EAAA;AAClB,EAAA;AAC+B,IAAA;AAC/B,MAAA;AAAA,gFAAA;AAEF,IAAA;AACgC,IAAA;AACX,IAAA;AACI,IAAA;AACnB,MAAA;AAC+C,QAAA;AACnD,MAAA;AACK,IAAA;AACD,MAAA;AACyC,QAAA;AAC7C,MAAA;AACF,IAAA;AACM,EAAA;AAER,EAAA;AACF;AAE8B;AAClB,EAAA;AACE,IAAA;AACR,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAEgC;AAC6B,EAAA;AACpD,EAAA;AACT;AAEqD;AACzC,EAAA;AACH,EAAA;AACD,EAAA;AACO,EAAA;AACf;AJgLyE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-DUADUR6R.cjs","sourcesContent":[null,"import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from 'pino';\n\nexport interface RequestContext {\n user?: Record<string, unknown> | undefined;\n requestId?: string;\n log?: Logger;\n /** Model operations run so far in this request, by `Model.op` (N+1 detection). */\n queryCounts?: Map<string, number>;\n}\n\nconst storage = new AsyncLocalStorage<RequestContext>();\n\n// Wraps one request's lifecycle in an AsyncLocalStorage context. Node propagates\n// the store through the async chain the callback initiates (awaits, .then, etc.),\n// so anything running as part of the same request — including a `$currentUser`\n// default resolved deep inside a mongoose `.create()` call — can read it back.\nexport function runWithContext<T>(ctx: RequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getRequestContext(): RequestContext | undefined {\n return storage.getStore();\n}\n\nexport function setCurrentUser(user: Record<string, unknown> | undefined): void {\n const store = storage.getStore();\n if (store) store.user = user;\n}\n\nexport function getCurrentUser(): Record<string, unknown> | undefined {\n return storage.getStore()?.user;\n}\n","import cluster from 'node:cluster';\nimport { randomUUID } from 'node:crypto';\nimport type { RequestHandler } from 'express';\nimport pc from 'picocolors';\nimport { pino, type Logger, type DestinationStream } from 'pino';\nimport type { LoggingConfig } from './types.js';\nimport { getRequestContext } from './context.js';\n\nexport type { Logger };\n\nconst LEVEL_LABELS: Record<number, string> = {\n 10: pc.gray('TRACE'),\n 20: pc.blue('DEBUG'),\n 30: pc.green('INFO '),\n 40: pc.yellow('WARN '),\n 50: pc.red('ERROR'),\n 60: pc.bgRed('FATAL'),\n};\n\nconst OMIT = new Set(['level', 'time', 'msg', 'pid', 'hostname', 'worker', 'reqId']);\n\n// Dev-friendly one-line renderer, so readable output doesn't need pino-pretty or a\n// transport worker thread: `12:00:01 INFO [w2] a1b2c3d4 GET /users 200 (3ms)`.\nfunction prettyStream(out: NodeJS.WritableStream = process.stdout): DestinationStream {\n return {\n write(line: string) {\n let rec: Record<string, unknown>;\n try {\n rec = JSON.parse(line) as Record<string, unknown>;\n } catch {\n out.write(line);\n return;\n }\n const time = new Date(rec['time'] as number).toTimeString().slice(0, 8);\n const level = LEVEL_LABELS[rec['level'] as number] ?? String(rec['level']);\n const worker = rec['worker'] !== undefined ? pc.dim(`[${String(rec['worker'])}] `) : '';\n const reqId = rec['reqId'] ? pc.magenta(String(rec['reqId']).slice(0, 8)) + ' ' : '';\n const extra = Object.entries(rec).filter(([k]) => !OMIT.has(k));\n const err = rec['err'] as { stack?: string } | undefined;\n const fields = extra\n .filter(([k]) => k !== 'err')\n .map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`)\n .join(' ');\n out.write(\n `${pc.dim(time)} ${level} ${worker}${reqId}${String(rec['msg'] ?? '')}` +\n (fields ? ' ' + pc.dim(fields) : '') +\n (err?.stack ? '\\n' + pc.red(err.stack) : '') +\n '\\n',\n );\n },\n };\n}\n\nfunction workerLabel(): string {\n return cluster.isWorker ? `w${cluster.worker?.id ?? '?'}` : 'primary';\n}\n\nfunction build(config: LoggingConfig | false | undefined): Logger {\n if (config === false) return pino({ level: 'silent' });\n const opts = config ?? {};\n const pretty =\n opts.pretty ?? (process.env['NODE_ENV'] !== 'production' && process.stdout.isTTY === true);\n const base = { worker: workerLabel() };\n const level = opts.level ?? 'info';\n return pretty\n ? pino({ level, base, errorKey: 'err' }, prettyStream())\n : pino({ level, base, errorKey: 'err', timestamp: pino.stdTimeFunctions.isoTime });\n}\n\nlet rootLogger: Logger = build(undefined);\nlet logRequests = true;\n\n/** Called by ignite() during Pre-Flight; before that the defaults apply. */\nexport function configureLogger(config: LoggingConfig | false | undefined): void {\n rootLogger = build(config);\n logRequests = config !== false && (config?.requests ?? true);\n}\n\n/**\n * The logger for the current scope: inside a request it is a child carrying that\n * request's `reqId`, so everything logged while handling it can be correlated;\n * elsewhere (startup, task handlers, timers) it is the root logger.\n */\nexport function getLogger(): Logger {\n return getRequestContext()?.log ?? rootLogger;\n}\n\n/** Root logger proxy — always reflects the latest configureLogger() call. */\nexport const logger: Logger = new Proxy({} as Logger, {\n get(_t, prop) {\n const target = getLogger() as unknown as Record<PropertyKey, unknown>;\n const value = target[prop];\n return typeof value === 'function'\n ? (value as (...a: unknown[]) => unknown).bind(target)\n : value;\n },\n});\n\nconst SAFE_REQUEST_ID = /^[\\w.:-]{1,128}$/;\n\n/**\n * Assigns the request ID (trusting a well-formed incoming `X-Request-Id`, e.g. from\n * a load balancer), echoes it back, attaches `req.id` / `req.log`, and logs one\n * line per completed request. Must run inside the request's context.\n */\nexport function requestLogger(): RequestHandler {\n return (req, res, next) => {\n const incoming = req.get('x-request-id');\n const id = incoming && SAFE_REQUEST_ID.test(incoming) ? incoming : randomUUID();\n const log = rootLogger.child({ reqId: id });\n\n req.id = id;\n req.log = log;\n res.setHeader('X-Request-Id', id);\n const ctx = getRequestContext();\n if (ctx) {\n ctx.requestId = id;\n ctx.log = log;\n }\n\n if (logRequests) {\n const start = process.hrtime.bigint();\n res.on('finish', () => {\n const durationMs = Number(process.hrtime.bigint() - start) / 1e6;\n const status = res.statusCode;\n const line = {\n method: req.method,\n url: req.originalUrl,\n status,\n durationMs: Math.round(durationMs * 10) / 10,\n };\n const msg = `${req.method} ${req.originalUrl} ${status}`;\n if (status >= 500) log.error(line, msg);\n else if (status >= 400) log.warn(line, msg);\n else log.info(line, msg);\n });\n }\n next();\n };\n}\n\ndeclare module 'express-serve-static-core' {\n interface Request {\n /** Request ID — the incoming `X-Request-Id` if well-formed, else a UUID. */\n id: string;\n /** Logger bound to this request's ID. */\n log: Logger;\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { LoggingConfig } from '../types.js';\nimport { getRequestContext } from '../context.js';\nimport { getLogger } from '../logger.js';\n\n// Query logging (`logging.queries`): one event per model operation — model, operation,\n// duration, how many database statements it issued, and the request ID — plus slow-query\n// warnings and an N+1 detector. Statements are counted at the driver: Drizzle's logger on\n// PostgreSQL, mongoose's debug hook on MongoDB.\n\n/** One finished model operation. */\nexport interface QueryEvent {\n model: string;\n op: string;\n durationMs: number;\n /** Database statements (SQL statements / MongoDB commands) issued, nested calls included. */\n statements: number;\n /** The request it ran in, if any. */\n reqId?: string;\n /** Set when it threw. */\n error?: string;\n}\n\ninterface Resolved {\n all: boolean;\n slowMs: number;\n nPlusOne: number | false;\n}\n\nconst DEFAULTS = { slowMs: 500, nPlusOne: 10 } as const;\n\nlet config: Resolved | undefined;\nconst listeners = new Set<(event: QueryEvent) => void>();\nconst enableHooks: (() => void)[] = [];\n\n/** Called by ignite() during Pre-Flight, next to configureLogger(). */\nexport function configureQueryLog(logging: LoggingConfig | false | undefined): void {\n const q = logging === false ? undefined : logging?.queries;\n config = !q\n ? undefined\n : q === true\n ? { all: true, ...DEFAULTS }\n : {\n all: q.all ?? false,\n slowMs: q.slowMs ?? DEFAULTS.slowMs,\n nPlusOne: q.nPlusOne ?? DEFAULTS.nPlusOne,\n };\n if (config) for (const hook of enableHooks) hook();\n}\n\nfunction active(): boolean {\n return config !== undefined || listeners.size > 0;\n}\n\n/**\n * Receives every model operation while subscribed (whether or not `logging.queries` is\n * on). Returns the unsubscribe function. Internal — tests use it to count statements.\n */\nexport function onQuery(listener: (event: QueryEvent) => void): () => void {\n listeners.add(listener);\n for (const hook of enableHooks) hook();\n return () => listeners.delete(listener);\n}\n\n/** Registers a driver hook to install once query tracking is first needed. */\nexport function whenQueryTracking(install: () => void): void {\n enableHooks.push(install);\n if (active()) install();\n}\n\ninterface Frame {\n statements: number;\n parent: Frame | undefined;\n}\n\nconst frames = new AsyncLocalStorage<Frame | undefined>();\n\n/** Called by the driver hooks for each statement sent to the database. */\nexport function countStatement(): void {\n for (let f = frames.getStore(); f; f = f.parent) f.statements++;\n}\n\n/** Runs `fn` outside any operation, so its statements (e.g. auto-sync) are not counted. */\nexport function untracked<R>(fn: () => R): R {\n return frames.run(undefined, fn);\n}\n\n// The first stack frame outside EFC: the line in the app that made the call.\nfunction callSite(callee: (...args: never[]) => unknown): string | undefined {\n const holder: { stack?: string } = {};\n Error.captureStackTrace(holder, callee);\n const line = holder.stack?.split('\\n')[1];\n return line?.trim().replace(/^at /, '');\n}\n\nfunction emit(event: QueryEvent, site: string | undefined, top: boolean): void {\n for (const listener of listeners) listener(event);\n if (!config) return;\n const log = getLogger();\n const msg = `${event.model}.${event.op} ${event.durationMs}ms`;\n // The request's logger already carries reqId.\n const fields: Partial<QueryEvent> = { ...event };\n delete fields.reqId;\n if (event.durationMs >= config.slowMs) {\n log.warn({ ...fields, slow: true }, `Slow query: ${msg}`);\n } else if (config.all) {\n log.info(fields, msg);\n }\n if (top && config.nPlusOne !== false) detectNPlusOne(event, site, config.nPlusOne);\n}\n\nfunction detectNPlusOne(event: QueryEvent, site: string | undefined, threshold: number): void {\n const ctx = getRequestContext();\n if (!ctx) return;\n const key = `${event.model}.${event.op}`;\n const counts = (ctx.queryCounts ??= new Map());\n const n = (counts.get(key) ?? 0) + 1;\n counts.set(key, n);\n if (n !== threshold) return;\n getLogger().warn(\n { model: event.model, op: event.op, count: n, ...(site !== undefined && { site }) },\n `Possible N+1: ${key} ran ${n} times in one request — load them in one query instead`,\n );\n}\n\n/**\n * Wraps a model's public operations so each call is timed, its statements counted and\n * the result reported. A no-op wrapper while query logging is off.\n */\nexport function traceOps<M extends object>(model: string, target: M, ops: readonly string[]): M {\n const t = target as Record<string, unknown>;\n for (const op of ops) {\n const fn = t[op] as (...args: unknown[]) => Promise<unknown>;\n const traced = function (this: unknown, ...args: unknown[]): Promise<unknown> {\n if (!active()) return fn.apply(this, args);\n const parent = frames.getStore();\n const frame: Frame = { statements: 0, parent };\n // Only N+1 checks need the call site; capture it while the caller is on the stack.\n const site = !parent && config && config.nPlusOne !== false ? callSite(traced) : undefined;\n const start = process.hrtime.bigint();\n const finish = (error?: unknown) => {\n const durationMs = Math.round(Number(process.hrtime.bigint() - start) / 1e5) / 10;\n const reqId = getRequestContext()?.requestId;\n emit(\n {\n model,\n op,\n durationMs,\n statements: frame.statements,\n ...(reqId !== undefined && { reqId }),\n ...(error !== undefined && { error: (error as Error)?.message ?? String(error) }),\n },\n site,\n !parent,\n );\n };\n return frames\n .run(frame, () => fn.apply(this, args))\n .then(\n (result) => {\n finish();\n return result;\n },\n (err: unknown) => {\n finish(err);\n throw err;\n },\n );\n };\n t[op] = traced;\n }\n return target;\n}\n","import type { Pool } from 'pg';\nimport { getLogger } from '../logger.js';\nimport { countStatement } from './query-log.js';\nimport type { DatabasePoolConfig } from '../types.js';\n\n// Pre-Flight's PostgreSQL connection: a node-postgres Pool (exposed as `db`) plus a\n// Drizzle instance over it that the model adapter queries through.\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- drizzle is an optional peer, loaded dynamically */\nlet pool: Pool | undefined;\n\n/** Only a genuinely missing package becomes \"not installed\"; other load errors surface as-is. */\nexport function notInstalled(err: unknown, pkg: string, install: string): Error {\n const code = (err as { code?: string }).code;\n return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND'\n ? new Error(`[EFC] ${pkg} is not installed. Run: ${install}`)\n : (err as Error);\n}\nlet orm: any;\n\nexport async function connectPostgres(\n url: string,\n poolConfig: DatabasePoolConfig = {},\n): Promise<Pool> {\n let PoolCtor: typeof Pool;\n try {\n const pg = (await import('pg')) as unknown as {\n default?: { Pool: typeof Pool };\n Pool?: typeof Pool;\n };\n PoolCtor = (pg.default?.Pool ?? pg.Pool)!;\n } catch (err) {\n throw notInstalled(err, 'pg', 'npm install pg drizzle-orm');\n }\n let drizzle: (client: Pool, config: object) => unknown;\n try {\n ({ drizzle } = (await import('drizzle-orm/node-postgres')) as unknown as {\n drizzle: (client: Pool, config: object) => unknown;\n });\n } catch (err) {\n throw notInstalled(err, 'drizzle-orm', 'npm install drizzle-orm');\n }\n\n const next = new PoolCtor({\n connectionString: url,\n ...(poolConfig.max !== undefined && { max: poolConfig.max }),\n ...(poolConfig.idleTimeoutMs !== undefined && { idleTimeoutMillis: poolConfig.idleTimeoutMs }),\n ...(poolConfig.connectionTimeoutMs !== undefined && {\n connectionTimeoutMillis: poolConfig.connectionTimeoutMs,\n }),\n });\n // Idle-client errors (e.g. the server restarting) are emitted on the pool; unhandled\n // they would crash the process.\n next.on('error', (err) => getLogger().error({ err }, 'PostgreSQL pool error'));\n try {\n await next.query('select 1');\n } catch (err) {\n await next.end().catch(() => {});\n throw explainPostgresError(err, url);\n }\n pool = next;\n // Every model statement goes through Drizzle, in or out of a transaction: count it.\n orm = drizzle(next, { logger: { logQuery: countStatement } });\n getLogger().info('PostgreSQL connected');\n return next;\n}\n\n/** Where a connection string points, without the password (for error messages). */\nfunction describeUrl(url: string): { where: string; user: string; database: string } {\n try {\n const u = new URL(url);\n const database = decodeURIComponent(u.pathname.slice(1)) || '(default)';\n return {\n where: `${u.hostname || 'localhost'}:${u.port || '5432'}`,\n user: decodeURIComponent(u.username) || '(none)',\n database,\n };\n } catch {\n return { where: '(unparsable DATABASE_URL)', user: '?', database: '?' };\n }\n}\n\n/**\n * node-postgres' connection errors, said in terms of DATABASE_URL — e.g. a URL with no password\n * surfaces from pg as \"SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string\".\n * Unrecognised errors come back unchanged. The original is kept as `cause`.\n */\nexport function explainPostgresError(err: unknown, url: string): Error {\n const e = err as { code?: string; message?: string };\n const msg = e.message ?? '';\n const { where, user, database } = describeUrl(url);\n const hosted = 'For Neon, Supabase or RDS, copy the full connection string from the dashboard.';\n let text: string | undefined;\n if (/client password must be a string/.test(msg)) {\n text = `PostgreSQL asked for a password and DATABASE_URL has none (user \"${user}\" at ${where}). Put it in the URL: postgres://${user === '(none)' ? 'user' : user}:<password>@${where}/${database === '(default)' ? 'db' : database}. ${hosted}`;\n } else if (e.code === '28P01') {\n text = `PostgreSQL rejected the password for user \"${user}\" at ${where}. Check DATABASE_URL (special characters in the password must be URL-encoded). ${hosted}`;\n } else if (e.code === '28000' && /role .* does not exist/.test(msg)) {\n text = `PostgreSQL has no user \"${user}\" at ${where}. Create it (CREATE ROLE ${user} LOGIN PASSWORD '…';) or fix the user in DATABASE_URL.`;\n } else if (/no pg_hba\\.conf entry.*no encryption/.test(msg)) {\n text = `PostgreSQL at ${where} only accepts encrypted connections. Add ?sslmode=require to DATABASE_URL.`;\n } else if (e.code === '28000') {\n text = `PostgreSQL at ${where} refused user \"${user}\": ${msg}`;\n } else if (e.code === '3D000') {\n text = `Database \"${database}\" does not exist at ${where}. Create it first: createdb ${database} (or CREATE DATABASE \"${database}\";).`;\n } else if (/does not support SSL/.test(msg)) {\n text = `PostgreSQL at ${where} doesn't support SSL. Remove sslmode / ssl from DATABASE_URL (local servers usually run without it).`;\n } else if (e.code === 'ECONNREFUSED') {\n text = `Nothing is accepting connections at ${where}. Is PostgreSQL running, and is the host/port in DATABASE_URL right?`;\n } else if (e.code === 'ENOTFOUND' || e.code === 'EAI_AGAIN') {\n text = `Can't resolve the PostgreSQL host in DATABASE_URL (${where}). Check the hostname.`;\n } else if (e.code === 'ETIMEDOUT' || /timeout/i.test(msg)) {\n text = `Timed out connecting to PostgreSQL at ${where}. Check the host, and that a firewall / the provider's IP allow-list lets this machine in.`;\n }\n return text ? new Error(`[EFC] ${text}`, { cause: err }) : (err as Error);\n}\n\n/**\n * Every cluster worker opens its own pools, so a machine's total is `workers × (pool + …)`.\n * Logs that total against the server's limit, warning when this machine alone can exhaust it.\n * Best effort: a failure to read the limit is ignored.\n */\nexport async function checkConnectionBudget(\n perMachine: number,\n breakdown: string,\n): Promise<void> {\n const log = getLogger();\n try {\n const { rows } = await getPool().query<{ max: number; reserved: number }>(\n `select current_setting('max_connections')::int as max,\n current_setting('superuser_reserved_connections')::int as reserved`,\n );\n const { max, reserved } = rows[0]!;\n const usable = max - reserved;\n if (perMachine > usable) {\n log.warn(\n `[EFC] PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}), but the server allows ${usable} (max_connections ${max} − ${reserved} reserved). Under load, queries will fail with \"too many clients\". Lower databasePool.max or workers, or put PgBouncer in front.`,\n );\n } else {\n log.info(\n `PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}) of ${usable} allowed — multiply by your instance count if you run several`,\n );\n }\n } catch {\n /* can't read the limit (permissions, pooler) — nothing to compare against */\n }\n}\n\nexport function getOrm(): any {\n if (!orm) {\n throw new Error(\n '[EFC] PostgreSQL not connected — set database/databaseUrl in ignite() (or call connectPostgres)',\n );\n }\n return orm;\n}\n\nexport function getPool(): Pool {\n if (!pool) throw new Error('[EFC] PostgreSQL not connected');\n return pool;\n}\n\nexport async function closePostgres(): Promise<void> {\n const p = pool;\n pool = undefined;\n orm = undefined;\n await p?.end();\n}\n"]}
@@ -34,9 +34,10 @@ function modelFile(model) {
34
34
  );
35
35
  const opts = Object.keys(options).length ? `
36
36
  ${literal(options, " ")},` : "";
37
- return `import { defineTable } from 'express-file-cluster';
37
+ const api = model.api ?? "defineTable";
38
+ return `import { ${api} } from 'express-file-cluster';
38
39
 
39
- ${notes}export const ${model.name} = defineTable(
40
+ ${notes}export const ${model.name} = ${api}(
40
41
  '${model.name}',
41
42
  {
42
43
  ${fields}
@@ -44,10 +45,10 @@ ${fields}
44
45
  );
45
46
  `;
46
47
  }
47
- function modelIndex(names, typescript) {
48
+ function modelIndex(names, typescript, tables = true) {
48
49
  const sorted = [...names].sort();
49
50
  const exports = sorted.map((n) => `export { ${n} } from './${n}.js';`).join("\n");
50
- if (!typescript) return `${exports}
51
+ if (!typescript || !tables) return `${exports}
51
52
  `;
52
53
  return `${exports}
53
54
 
@@ -79,7 +80,8 @@ function writeModels(dir, models, opts) {
79
80
  `index.${ext}`,
80
81
  modelIndex(
81
82
  models.map((m) => m.name),
82
- opts.typescript
83
+ opts.typescript,
84
+ models.some((m) => (m.api ?? "defineTable") === "defineTable")
83
85
  )
84
86
  );
85
87
  return { written, skipped };
@@ -110,4 +112,4 @@ export {
110
112
  singular,
111
113
  plural
112
114
  };
113
- //# sourceMappingURL=chunk-BBSZLGZW.js.map
115
+ //# sourceMappingURL=chunk-EGSSZUVO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/db/codegen.ts"],"sourcesContent":["// Writes model files from a plain description — shared by `efc db pull` (introspected\n// PostgreSQL → defineTable, sampled MongoDB → defineCollection) and `efc import-prisma`.\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nexport interface ModelSource {\n name: string;\n /** Field name → definition, in column order. */\n fields: [string, unknown][];\n /** defineTable options (empty keys are left out). */\n options: Record<string, unknown>;\n /** Comments put above the model — what couldn't be carried over. */\n notes: string[];\n /** Default `defineTable`. */\n api?: 'defineTable' | 'defineCollection';\n}\n\nconst IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst key = (k: string) =>\n IDENT.test(k) ? k : `'${k.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n\nfunction literal(v: unknown, indent: string): string {\n if (typeof v === 'string') return `'${v.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n if (typeof v === 'number' || typeof v === 'boolean') return String(v);\n if (typeof v === 'bigint') return `${v}n`;\n if (v === null) return 'null';\n if (Array.isArray(v)) {\n const items = v.map((x) => literal(x, indent));\n const flat = `[${items.join(', ')}]`;\n return flat.length <= 80 && !flat.includes('\\n')\n ? flat\n : `[\\n${items.map((i) => `${indent} ${i},`).join('\\n')}\\n${indent}]`;\n }\n const entries = Object.entries(v as Record<string, unknown>).filter(([, x]) => x !== undefined);\n if (entries.length === 0) return '{}';\n const flat = `{ ${entries.map(([k, x]) => `${key(k)}: ${literal(x, indent)}`).join(', ')} }`;\n if (flat.length <= 80 && !flat.includes('\\n')) return flat;\n return `{\\n${entries.map(([k, x]) => `${indent} ${key(k)}: ${literal(x, `${indent} `)},`).join('\\n')}\\n${indent}}`;\n}\n\nexport function modelFile(model: ModelSource): string {\n const notes = model.notes.map((n) => `// ${n}\\n`).join('');\n const fields = model.fields\n .map(([name, def]) => ` ${key(name)}: ${literal(def, ' ')},`)\n .join('\\n');\n const options = Object.fromEntries(\n Object.entries(model.options).filter(\n ([, v]) =>\n v !== undefined && !(typeof v === 'object' && v !== null && Object.keys(v).length === 0),\n ),\n );\n const opts = Object.keys(options).length ? `\\n ${literal(options, ' ')},` : '';\n const api = model.api ?? 'defineTable';\n return `import { ${api} } from 'express-file-cluster';\n\n${notes}export const ${model.name} = ${api}(\n '${model.name}',\n {\n${fields}\n },${opts}\n);\n`;\n}\n\n/**\n * The barrel that registers every model and, in TypeScript, declares `Tables` for\n * `include` (defineTable only — `tables: false` for collections).\n */\nexport function modelIndex(names: string[], typescript: boolean, tables = true): string {\n const sorted = [...names].sort();\n const exports = sorted.map((n) => `export { ${n} } from './${n}.js';`).join('\\n');\n if (!typescript || !tables) return `${exports}\\n`;\n return `${exports}\n\n${sorted.map((n) => `import type { ${n} } from './${n}.js';`).join('\\n')}\n\n// Types \\`include\\` results: relations name models by string, this maps the names to models.\ndeclare module 'express-file-cluster' {\n interface Tables {\n${sorted.map((n) => ` ${n}: typeof ${n};`).join('\\n')}\n }\n}\n`;\n}\n\n/** Writes the models (and index) into `dir`; existing files are kept unless `force`. */\nexport function writeModels(\n dir: string,\n models: ModelSource[],\n opts: { typescript: boolean; force?: boolean },\n): { written: string[]; skipped: string[] } {\n const ext = opts.typescript ? 'ts' : 'js';\n fs.mkdirSync(dir, { recursive: true });\n const written: string[] = [];\n const skipped: string[] = [];\n const put = (file: string, content: string) => {\n const p = path.join(dir, file);\n if (fs.existsSync(p) && !opts.force) skipped.push(p);\n else {\n fs.writeFileSync(p, content);\n written.push(p);\n }\n };\n for (const m of models) put(`${m.name}.${ext}`, modelFile(m));\n put(\n `index.${ext}`,\n modelIndex(\n models.map((m) => m.name),\n opts.typescript,\n models.some((m) => (m.api ?? 'defineTable') === 'defineTable'),\n ),\n );\n return { written, skipped };\n}\n\n// ── Naming ───────────────────────────────────────────────────────────────────\n\nexport const pascal = (s: string) =>\n s\n .split(/[^A-Za-z0-9]+|_/)\n .filter(Boolean)\n .map((w) => w[0]!.toUpperCase() + w.slice(1))\n .join('');\n\nexport const camel = (s: string) => {\n const p = pascal(s);\n return p ? p[0]!.toLowerCase() + p.slice(1) : s;\n};\n\nexport const lcFirst = (s: string) => s[0]!.toLowerCase() + s.slice(1);\n\nexport function singular(word: string): string {\n if (/[^aeiou]ies$/i.test(word)) return word.slice(0, -3) + 'y';\n if (/(s|x|z|ch|sh)es$/i.test(word)) return word.slice(0, -2);\n if (/[^s]s$/i.test(word)) return word.slice(0, -1);\n return word;\n}\n\nexport function plural(word: string): string {\n if (/[^aeiou]y$/i.test(word)) return word.slice(0, -1) + 'ies';\n if (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AAM,CAAC,IAAI;AAChD;AAEO,IAAM,UAAU,CAAC,MAAc,EAAE,CAAC,EAAG,YAAY,IAAI,EAAE,MAAM,CAAC;AAE9D,SAAS,SAAS,MAAsB;AAC7C,MAAI,gBAAgB,KAAK,IAAI,EAAG,QAAO,KAAK,MAAM,GAAG,EAAE,IAAI;AAC3D,MAAI,oBAAoB,KAAK,IAAI,EAAG,QAAO,KAAK,MAAM,GAAG,EAAE;AAC3D,MAAI,UAAU,KAAK,IAAI,EAAG,QAAO,KAAK,MAAM,GAAG,EAAE;AACjD,SAAO;AACT;AAEO,SAAS,OAAO,MAAsB;AAC3C,MAAI,cAAc,KAAK,IAAI,EAAG,QAAO,KAAK,MAAM,GAAG,EAAE,IAAI;AACzD,MAAI,kBAAkB,KAAK,IAAI,EAAG,QAAO,OAAO;AAChD,SAAO,OAAO;AAChB;","names":["flat"]}
@@ -20,7 +20,10 @@ var _impl = null;
20
20
  function setEnqueueImpl(impl) {
21
21
  _impl = impl;
22
22
  }
23
+ var ENQUEUE_BRIDGE = /* @__PURE__ */ Symbol.for("efc.enqueueBridge");
23
24
  async function enqueue(name, payload) {
25
+ const bridge = globalThis[ENQUEUE_BRIDGE];
26
+ if (!_impl && bridge) return bridge(name, payload);
24
27
  if (!_impl) {
25
28
  throw new Error(
26
29
  `[EFC] Cannot enqueue task "${name}": task queue not initialised. Set tasks.backend in ignite() config.`
@@ -42,5 +45,6 @@ function listTasks() {
42
45
 
43
46
 
44
47
 
45
- exports.taskRegistry = taskRegistry; exports.defineTask = defineTask; exports.setEnqueueImpl = setEnqueueImpl; exports.enqueue = enqueue; exports.registerTask = registerTask; exports.listTasks = listTasks;
46
- //# sourceMappingURL=chunk-TI24L4XE.cjs.map
48
+
49
+ exports.taskRegistry = taskRegistry; exports.defineTask = defineTask; exports.setEnqueueImpl = setEnqueueImpl; exports.ENQUEUE_BRIDGE = ENQUEUE_BRIDGE; exports.enqueue = enqueue; exports.registerTask = registerTask; exports.listTasks = listTasks;
50
+ //# sourceMappingURL=chunk-GBI77W5T.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-GBI77W5T.cjs","../src/tasks/index.ts"],"names":[],"mappings":"AAAA;ACEO,IAAM,aAAA,kBAAe,IAAI,GAAA,CAA4B,CAAA;AAQrD,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;AAGA,IAAI,MAAA,EAA4B,IAAA;AAEzB,SAAS,cAAA,CAAe,IAAA,EAAyB;AACtD,EAAA,MAAA,EAAQ,IAAA;AACV;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,MAAA,GAAS,MAAA,EAAQ,OAAO,MAAA,CAAO,IAAA,EAAM,OAAkB,CAAA;AAC5D,EAAA,GAAA,CAAI,CAAC,KAAA,EAAO;AACV,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,2BAAA,EAA8B,IAAI,CAAA,oEAAA;AAAA,IACpC,CAAA;AAAA,EACF;AACA,EAAA,OAAO,KAAA,CAAM,IAAA,EAAM,OAAkB,CAAA;AACvC;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;AD5BA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sPAAC","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-GBI77W5T.cjs","sourcesContent":[null,"import type { TaskDefinition, TaskOptions } from '../types.js';\n\nexport const taskRegistry = new Map<string, TaskDefinition>();\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\ntype EnqueueImpl = (name: string, payload: unknown) => Promise<void>;\nlet _impl: EnqueueImpl | null = null;\n\nexport function setEnqueueImpl(impl: EnqueueImpl): void {\n _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 (!_impl && bridge) return bridge(name, payload as unknown);\n if (!_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 _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"]}