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
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/tasks/thread-runner.ts"],"sourcesContent":["import { Worker, workerData, parentPort, isMainThread } from 'node:worker_threads';\nimport type { TaskDefinition } from '../types.js';\nimport { enqueue, ENQUEUE_BRIDGE } from './index.js';\n\n// `{ thread: true }` tasks run here, in a worker_thread. The task queue lives on the main\n// thread, so `enqueue()` inside the thread is bridged: the thread posts the call, the main\n// thread runs the real enqueue() and posts back the outcome.\n\ntype FromThread =\n | { type: 'done'; ok: true }\n | { type: 'done'; ok: false; error: string }\n | { type: 'enqueue'; id: number; name: string; payload: unknown };\ntype ToThread = { type: 'enqueued'; id: number; error?: string };\n\n// ── Worker-thread side ────────────────────────────────────────────────────────\nif (!isMainThread && parentPort && (workerData as { efcTask?: boolean })?.efcTask) {\n const port = parentPort;\n const { handlerPath, payload } = workerData as { handlerPath: string; payload: unknown };\n const waiting = new Map<number, { resolve: () => void; reject: (e: Error) => void }>();\n let seq = 0;\n // The port only keeps the thread alive while an enqueue waits for its answer, so a\n // finished task's thread still exits.\n port.unref();\n port.on('message', (msg: ToThread) => {\n if (msg?.type !== 'enqueued') return;\n const w = waiting.get(msg.id);\n if (!w) return;\n waiting.delete(msg.id);\n if (waiting.size === 0) port.unref();\n if (msg.error === undefined) w.resolve();\n else w.reject(new Error(msg.error));\n });\n // On globalThis, so the task's own copy of express-file-cluster/tasks (ESM or CJS)\n // finds it too.\n (globalThis as Record<symbol, unknown>)[ENQUEUE_BRIDGE] = (name: string, payload: unknown) =>\n new Promise<void>((resolve, reject) => {\n const id = ++seq;\n waiting.set(id, { resolve, reject });\n port.ref();\n port.postMessage({ type: 'enqueue', id, name, payload } satisfies FromThread);\n });\n\n (async () => {\n try {\n const mod = (await import(handlerPath)) as Record<string, unknown>;\n const def = mod['default'] as TaskDefinition | undefined;\n if (!def || typeof def.handler !== 'function') {\n throw new Error(`[EFC] Thread runner: no valid task export in ${handlerPath}`);\n }\n await def.handler(payload);\n port.postMessage({ type: 'done', ok: true } satisfies FromThread);\n } catch (err) {\n port.postMessage({ type: 'done', ok: false, error: String(err) } satisfies FromThread);\n }\n })();\n}\n\n// ── Main-thread side ──────────────────────────────────────────────────────────\nexport function runInThread(handlerPath: string, payload: unknown): Promise<void> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(new URL('./thread-runner.js', import.meta.url), {\n workerData: { efcTask: true, handlerPath, payload },\n });\n\n worker.on('message', (msg: FromThread) => {\n if (msg.type === 'enqueue') {\n const reply = (error?: string) =>\n worker.postMessage({\n type: 'enqueued',\n id: msg.id,\n ...(error !== undefined && { error }),\n } satisfies ToThread);\n enqueue(msg.name, msg.payload).then(\n () => reply(),\n (err: unknown) => reply(err instanceof Error ? err.message : String(err)),\n );\n return;\n }\n if (msg.ok) resolve();\n else reject(new Error(msg.error ?? 'Thread task failed'));\n });\n\n worker.on('error', reject);\n worker.on('exit', (code) => {\n if (code !== 0) reject(new Error(`Thread worker exited with code ${code}`));\n });\n });\n}\n"],"mappings":";;;;;;AAAA,SAAS,QAAQ,YAAY,YAAY,oBAAoB;AAe7D,IAAI,CAAC,gBAAgB,cAAe,YAAsC,SAAS;AACjF,QAAM,OAAO;AACb,QAAM,EAAE,aAAa,QAAQ,IAAI;AACjC,QAAM,UAAU,oBAAI,IAAiE;AACrF,MAAI,MAAM;AAGV,OAAK,MAAM;AACX,OAAK,GAAG,WAAW,CAAC,QAAkB;AACpC,QAAI,KAAK,SAAS,WAAY;AAC9B,UAAM,IAAI,QAAQ,IAAI,IAAI,EAAE;AAC5B,QAAI,CAAC,EAAG;AACR,YAAQ,OAAO,IAAI,EAAE;AACrB,QAAI,QAAQ,SAAS,EAAG,MAAK,MAAM;AACnC,QAAI,IAA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I,OAAO,EAAE;AAAA,UAC7B,MAAM,MAAM;AAAA,UACZ,CAAC,QAAiB,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,QAC1E;AACA;AAAA,MACF;AACA,UAAI,IAAI,GAAI,SAAQ;AAAA,UACf,QAAO,IAAI,MAAM,IAAI,SAAS,oBAAoB,CAAC;AAAA,IAC1D,CAAC;AAED,WAAO,GAAG,SAAS,MAAM;AACzB,WAAO,GAAG,QAAQ,CAAC,SAAS;AAC1B,UAAI,SAAS,EAAG,QAAO,IAAI,MAAM,kCAAkC,IAAI,EAAE,CAAC;AAAA,IAC5E,CAAC;AAAA,EACH,CAAC;AACH;","names":["payload"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-6WTMRZS7.cjs","../src/tasks/pgboss-backend.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACQA,IAAM,IAAA,EAAM,YAAA;AACZ,IAAM,IAAA,EAAM,CAAC,OAAA,EAAA,GACX,QAAA,IAAY,KAAA,GAAQ,OAAO,QAAA,IAAY,SAAA,GAAY,CAAC,KAAA,CAAM,OAAA,CAAQ,OAAO,EAAA,EACpE,QAAA,EACD,EAAE,CAAC,GAAG,CAAA,EAAG,QAAQ,CAAA;AACvB,IAAM,MAAA,EAAQ,CAAC,IAAA,EAAA,GACb,KAAA,IAAS,KAAA,GAAQ,OAAO,KAAA,IAAS,SAAA,GAAY,IAAA,GAAO,KAAA,EAC/C,IAAA,CAAiC,GAAG,EAAA,EACrC,IAAA;AAEN,IAAM,aAAA,EAAe,CAAC,GAAA,EAAA,GAAA,CAAyB;AAAA;AAAA,EAE7C,UAAA,mBAAY,GAAA,CAAI,OAAA,CAAQ,OAAA,UAAW,GAAA;AAAA,EACnC,UAAA,EAAY,CAAA;AAAA,E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AAsE,0DAAA;AAC0B,uDAAA;AAE1E,IAAA;AAExB,EAAA;AASsD,EAAA;AACzC,IAAA;AACO,IAAA;AACf,IAAA;AACT,EAAA;AAEO,EAAA;AACU,IAAA;AACU,MAAA;AACrB,QAAA;AACO,QAAA;AACT,MAAA;AACc,MAAA;AAC2C,QAAA;AACzD,MAAA;AACF,IAAA;AAC0B,IAAA;AACJ,MAAA;AACF,QAAA;AAClB,MAAA;AACqB,MAAA;AACA,QAAA;AACX,UAAA;AACa,UAAA;AACD,UAAA;AACD,UAAA;AACL,UAAA;AACA,UAAA;AACd,QAAA;AACF,MAAA;AACF,IAAA;AACiB,IAAA;AACI,MAAA;AACK,MAAA;AACZ,MAAA;AACd,IAAA;AACiB,IAAA;AACI,MAAA;AACK,MAAA;AACZ,MAAA;AACd,IAAA;AACc,IAAA;AACM,MAAA;AACpB,IAAA;AACF,EAAA;AACF;ADpD8B;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-6WTMRZS7.cjs","sourcesContent":[null,"import type { PgBoss as PgBossType } from 'pg-boss';\nimport type { TaskDefinition } from '../types.js';\nimport { taskRegistry, setEnqueueImpl } from './index.js';\nimport { runInThread } from './thread-runner.js';\nimport { getLogger } from '../logger.js';\nimport { explainPostgresError } from '../db/postgres.js';\nimport type { FailedJob, TaskAdmin } from './admin.js';\n\n// pg-boss keeps one queue per job name, so each task gets its own pg-boss queue\n// named `<tasks.queue>.<TaskName>` — the prefix keeps apps sharing a database apart.\n\ninterface PgBossOpts {\n connectionString: string;\n concurrency: number;\n enqueueTimeout: number;\n queue: string;\n schema?: string;\n}\n\n// pg-boss payloads must be objects; other values are boxed so any enqueue() payload works.\nconst BOX = '__efcValue';\nconst box = (payload: unknown): object =>\n payload !== null && typeof payload === 'object' && !Array.isArray(payload)\n ? (payload as object)\n : { [BOX]: payload };\nconst unbox = (data: unknown): unknown =>\n data !== null && typeof data === 'object' && BOX in data\n ? (data as Record<string, unknown>)[BOX]\n : data;\n\nconst retryOptions = (def: TaskDefinition) => ({\n // pg-boss's retryLimit counts re-runs, exactly like EFC's `retries`.\n retryLimit: def.options.retries ?? 3,\n retryDelay: 1,\n retryBackoff: (def.options.backoff ?? 'exponential') === 'exponential',\n});\n\nasync function loadPgBoss(): Promise<typeof PgBossType> {\n try {\n const mod = (await import('pg-boss')) as unknown as {\n PgBoss?: typeof PgBossType;\n default?: typeof PgBossType | { PgBoss: typeof PgBossType };\n };\n const ctor =\n mod.PgBoss ??\n (typeof mod.default === 'function'\n ? mod.default\n : (mod.default as { PgBoss: typeof PgBossType }).PgBoss);\n return ctor;\n } catch {\n throw new Error('[EFC] pg-boss is not installed. Run: npm install pg-boss');\n }\n}\n\nlet closeImpl: (() => Promise<void>) | null = null;\n\nexport async function closePgBoss(): Promise<void> {\n const close = closeImpl;\n closeImpl = null;\n await close?.();\n}\n\nexport async function initPgBoss(opts: PgBossOpts): Promise<void> {\n const PgBoss = await loadPgBoss();\n const boss = new PgBoss({\n connectionString: opts.connectionString,\n ...(opts.schema !== undefined && { schema: opts.schema }),\n });\n boss.on('error', (err: Error) => getLogger().error({ err }, 'pg-boss error'));\n try {\n await boss.start();\n } catch (err) {\n throw explainPostgresError(err, opts.connectionString);\n }\n\n const queueFor = (name: string) => `${opts.queue}.${name}`;\n const wantedSchedules = new Set<string>();\n\n for (const def of taskRegistry.values()) {\n const queue = queueFor(def.name);\n await boss.createQueue(queue, retryOptions(def));\n await boss.work(\n queue,\n { localConcurrency: def.options.concurrency ?? opts.concurrency },\n async (jobs: { id: string; data: unknown; retryCount: number }[]) => {\n for (const job of jobs) {\n const payload = unbox(job.data);\n try {\n if (def.options.thread && def.filePath) await runInThread(def.filePath, payload);\n else await def.handler(payload);\n getLogger().info({ task: def.name, jobId: job.id }, `Task ${def.name} completed`);\n } catch (err) {\n getLogger().error(\n { task: def.name, jobId: job.id, attempt: job.retryCount + 1, err },\n `Task ${def.name} failed`,\n );\n throw err;\n }\n }\n },\n );\n if (def.options.schedule) {\n wantedSchedules.add(queue);\n await boss.schedule(\n queue,\n def.options.schedule,\n {},\n {\n ...retryOptions(def),\n ...(def.options.timezone !== undefined && { tz: def.options.timezone }),\n },\n );\n }\n }\n\n // Drop schedules for tasks that lost their `schedule` or no longer exist.\n for (const s of await boss.getSchedules()) {\n if (s.name.startsWith(`${opts.queue}.`) && !wantedSchedules.has(s.name)) {\n await boss.unschedule(s.name);\n }\n }\n if (wantedSchedules.size > 0) getLogger().info(`Scheduled ${wantedSchedules.size} cron task(s)`);\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 let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `[EFC] Cannot enqueue task \"${name}\": PostgreSQL did not respond within ${opts.enqueueTimeout}ms`,\n ),\n ),\n opts.enqueueTimeout,\n );\n });\n try {\n await Promise.race([boss.send(queueFor(name), box(payload), retryOptions(def)), 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 closeImpl = async () => {\n // graceful: lets in-flight jobs finish before the connection pool closes.\n await boss.stop({ graceful: true, timeout: 10_000 });\n };\n\n getLogger().info('pg-boss backend initialised');\n}\n\n/** Dead-letter inspection for `efc tasks failed | retry | purge` on pg-boss. */\nexport async function pgBossAdmin(\n connectionString: string,\n queue = 'efc',\n schema = 'pgboss',\n): Promise<TaskAdmin> {\n const PgBoss = await loadPgBoss();\n // No supervision or cron here: this instance only reads and settles jobs.\n const boss = new PgBoss({\n connectionString,\n schema,\n supervise: false,\n schedule: false,\n migrate: false,\n });\n boss.on('error', () => {});\n await boss.start();\n const db = boss.getDb();\n const prefix = `${queue}.`;\n const taskOf = (name: string) => name.slice(prefix.length);\n const table = `\"${schema.replace(/\"/g, '\"\"')}\".job`;\n\n const failedRows = async (ids: string[], limit = 10_000) =>\n (\n await db.executeSql(\n `SELECT id, name, data, output, retry_count, completed_on FROM ${table}\n WHERE state = 'failed' AND starts_with(name, $1) ${ids.length ? 'AND id = ANY($3::uuid[])' : ''}\n ORDER BY completed_on DESC NULLS LAST LIMIT $2`,\n ids.length ? [prefix, limit, ids] : [prefix, limit],\n )\n ).rows as {\n id: string;\n name: string;\n data: unknown;\n output: unknown;\n retry_count: number;\n completed_on: Date | null;\n }[];\n\n const byQueue = (rows: { id: string; name: string }[]) => {\n const groups = new Map<string, string[]>();\n for (const r of rows) groups.set(r.name, [...(groups.get(r.name) ?? []), r.id]);\n return groups;\n };\n\n return {\n async counts() {\n const { rows } = await db.executeSql(\n `SELECT state, count(*)::int AS n FROM ${table} WHERE starts_with(name, $1) GROUP BY state`,\n [prefix],\n );\n return Object.fromEntries(\n (rows as { state: string; n: number }[]).map((r) => [r.state, r.n]),\n );\n },\n async listFailed({ limit, name }) {\n const rows = (await failedRows([], name ? 10_000 : limit)).filter(\n (r) => !name || taskOf(r.name) === name,\n );\n return rows.slice(0, limit).map(\n (r): FailedJob => ({\n id: r.id,\n name: taskOf(r.name),\n data: unbox(r.data),\n error: String((r.output as { message?: string } | null)?.message ?? r.output ?? ''),\n attempts: r.retry_count + 1,\n failedAt: r.completed_on ?? undefined,\n }),\n );\n },\n async retry(ids) {\n const rows = await failedRows(ids);\n for (const [q, list] of byQueue(rows)) await boss.retry(q, list);\n return rows.length;\n },\n async purge(ids) {\n const rows = await failedRows(ids);\n for (const [q, list] of byQueue(rows)) await boss.deleteJob(q, list);\n return rows.length;\n },\n async close() {\n await boss.stop({ graceful: false });\n },\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/tasks/index.ts"],"sourcesContent":["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"],"mappings":";AAEO,IAAM,eAAe,oBAAI,IAA4B;AAQrD,IAAM,aAAiC,CAC5C,kBACA,iBACsB;AACtB,MAAI,UAAuB,CAAC;AAC5B,MAAI;AAEJ,MAAI,OAAO,qBAAqB,YAAY;AAC1C,cAAU;AAAA,EACZ,OAAO;AACL,cAAU;AACV,QAAI,CAAC,aAAc,OAAM,IAAI,MAAM,gDAAgD;AACnF,cAAU;AAAA,EACZ;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,MAAM;AAAA,EACR;AACF;AAGA,IAAI,QAA4B;AAEzB,SAAS,eAAe,MAAyB;AACtD,UAAQ;AACV;AAGO,IAAM,iBAAiB,uBAAO,IAAI,mBAAmB;AAE5D,eAAsB,QAAW,MAAc,SAA2B;AACxE,QAAM,SAAU,WAAuC,cAAc;AACrE,MAAI,CAAC,SAAS,OAAQ,QAAO,OAAO,MAAM,OAAkB;AAC5D,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR,8BAA8B,IAAI;AAAA,IACpC;AAAA,EACF;AACA,SAAO,MAAM,MAAM,OAAkB;AACvC;AAEO,SAAS,aAAa,MAAc,KAA2B;AACpE,eAAa,IAAI,MAAM,EAAE,GAAG,KAAK,KAAK,CAAC;AACzC;AAUO,SAAS,YAAmE;AACjF,SAAO,MAAM,KAAK,aAAa,OAAO,CAAC,EAAE,IAAI,CAAC,EAAE,MAAM,QAAQ,OAAO,EAAE,MAAM,QAAQ,EAAE;AACzF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-CGY7JU4Y.cjs","../../../node_modules/tsup/assets/cjs_shims.js"],"names":[],"mappings":"AAAA;ACKA,IAAM,iBAAA,EAAmB,CAAA,EAAA,GACvB,OAAO,SAAA,IAAa,YAAA,EAChB,IAAI,GAAA,CAAI,CAAA,KAAA,EAAQ,UAAU,CAAA,CAAA;AAK8B;ADT4B;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-CGY7JU4Y.cjs","sourcesContent":[null,"// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-DGYPIIJE.cjs","../src/websocket.ts","../src/router/validate.ts","../src/router/mount.ts","../src/openapi.ts","../src/http-app.ts"],"names":["path"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACdA,wEAAiB;AAGjB,wBAA2C;AAqB3C,IAAM,QAAA,kBAAU,MAAA,CAAO,GAAA,CAAI,2CAA2C,CAAA;AAQtE,IAAM,QAAA,EAAU,4CAAA,mBAAa,EAAqB,CAAA,EAAA,mBAAM,IAAI,OAAA,CAA4B,CAAC,CAAA;AAClF,IAAM,UAAA,EAAY,CAAC,GAAA,EAAA,GAA0B,CAAC,CAAE,GAAA,CAAuB,OAAO,CAAA;AAG9E,IAAM,cAAA,EAAgC,CAAC,GAAA,EAAK,GAAA,EAAK,IAAA,EAAA,GAAS;AAC/D,EAAA,MAAM,QAAA,EAAW,GAAA,CAAuB,OAAO,CAAA;AAC/C,EAAA,GAAA,CAAI,CAAC,OAAA,EAAS,OAAO,IAAA,CAAK,OAAO,CAAA;AACjC,EAAA,MAAM,OAAA,EAAS,GAAA,CAAI,OAAA,CAAQ,MAAA;AAC3B,EAAA,GAAA,CAAI,OAAA,IAAW,KAAA,CAAA,EAAW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D,QAAA;AACzE,IAAA;AAC4C,IAAA;AACwC,IAAA;AAC3D,MAAA;AACL,MAAA;AACnB,IAAA;AACF,EAAA;AACyF,EAAA;AACpC,EAAA;AACpB,EAAA;AACK,IAAA;AACpB,IAAA;AAClB,EAAA;AACM,EAAA;AACT;AJ0Q6K;AACA;AK3vBzJ;AACH;AACQ;AAOyC;AACT,EAAA;AACnC,EAAA;AACyD,EAAA;AAGzE,EAAA;AAAI,IAAA;AACyC,IAAA;AACjD,EAAA;AAK8B,EAAA;AACL,IAAA;AACxB,EAAA;AACsB,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;AACxB,IAAA;AACZ,EAAA;AAEO,EAAA;AACT;AAKQ;AACO,EAAA;AACI,IAAA;AACV,EAAA;AACD,IAAA;AAC2F,MAAA;AAEtE,QAAA;AAC0C,UAAA;AAC7D,UAAA;AACF,QAAA;AAKyD,QAAA;AAInD,QAAA;AAEgB,QAAA;AAEyB,UAAA;AACb,UAAA;AACnB,YAAA;AACK,YAAA;AACqB,YAAA;AACtC,UAAA;AACmB,QAAA;AAGkD,UAAA;AACjE,QAAA;AACuC,UAAA;AAC4B,UAAA;AAC1E,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACF;AL4tB6K;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-DGYPIIJE.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 { Request, RequestHandler } from 'express';\nimport type { RequestSchema, RouteSchema, ValidationIssue, Validator } from '../types.js';\n\nconst LOCATIONS = ['params', 'query', 'body'] as const;\ntype Location = (typeof LOCATIONS)[number];\n\ninterface StandardResult {\n value?: unknown;\n issues?: ReadonlyArray<{\n message: string;\n path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n }>;\n}\n\nfunction isRequestSchema(value: unknown): value is RequestSchema {\n return (\n value != null &&\n typeof value === 'object' &&\n LOCATIONS.some((loc) => loc in (value as Record<string, unknown>))\n );\n}\n\n/** Picks the schema for `method`: a method-keyed entry wins over a file-wide one. */\nexport function schemaFor(\n schema: RouteSchema | undefined,\n method: string,\n): RequestSchema | undefined {\n if (!schema) return undefined;\n const byMethod = (schema as Record<string, unknown>)[method];\n if (isRequestSchema(byMethod)) return byMethod;\n return isRequestSchema(schema) ? schema : undefined;\n}\n\ntype IssuePath = ReadonlyArray<PropertyKey | { key: PropertyKey }> | undefined;\n\nfunction pathToString(path: IssuePath): string {\n if (!path) return '';\n return path\n .map((p) => (typeof p === 'object' && p !== null && 'key' in p ? p.key : p))\n .map(String)\n .join('.');\n}\n\n// Standard Schema (zod >=3.24, valibot, arktype, ...) first; plain zod-style\n// safeParse as a fallback so older zod 3 releases work too.\nasync function run(validator: Validator, input: unknown): Promise<StandardResult> {\n const std = (validator as { '~standard'?: { validate: (v: unknown) => unknown } })['~standard'];\n if (std && typeof std.validate === 'function') {\n return (await std.validate(input)) as StandardResult;\n }\n const v = validator as {\n safeParseAsync?: (x: unknown) => Promise<unknown>;\n safeParse?: (x: unknown) => unknown;\n };\n const parse = v.safeParseAsync ?? v.safeParse;\n if (typeof parse !== 'function') {\n throw new Error('[EFC] Route schema entries must be Standard Schema validators (e.g. zod)');\n }\n const r = (await parse.call(validator, input)) as {\n success: boolean;\n data?: unknown;\n error?: { issues: Array<{ message: string; path: PropertyKey[] }> };\n };\n return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: 'Invalid' }] };\n}\n\n/**\n * Validates params/query/body against the route's schema. On success the parsed\n * output replaces the raw input (so coercions and defaults apply); on failure\n * responds 400 with every issue across all locations.\n */\nexport function validateRequest(schema: RequestSchema): RequestHandler {\n return (req, res, next) => {\n void (async () => {\n const issues: ValidationIssue[] = [];\n const parsed: Partial<Record<Location, unknown>> = {};\n\n for (const location of LOCATIONS) {\n const validator = schema[location];\n if (!validator) continue;\n const result = await run(validator, req[location]);\n if (result.issues) {\n for (const issue of result.issues) {\n issues.push({ location, path: pathToString(issue.path), message: issue.message });\n }\n } else {\n parsed[location] = result.value;\n }\n }\n\n if (issues.length > 0) {\n res.status(400).json({ error: 'Validation failed', statusCode: 400, issues });\n return;\n }\n\n for (const location of LOCATIONS) {\n if (location in parsed) {\n // req.query is a getter in some Express setups — define rather than assign.\n Object.defineProperty(req as Request, location, {\n value: parsed[location],\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n next();\n })().catch(next);\n };\n}\n","import type { IRouter, RequestHandler } from 'express';\nimport type { MountedRoute, RouteMeta, RouteEntry, RouteSchema } from '../types.js';\nimport { schemaFor, validateRequest } from './validate.js';\nimport { isUpgrade, websocketOnly, websocketHandler, type WebSocketHandler } from '../websocket.js';\n\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const;\ntype HttpMethod = (typeof HTTP_METHODS)[number];\n\nfunction asyncWrap(handler: RequestHandler): RequestHandler {\n return (req, res, next) => {\n Promise.resolve(handler(req, res, next)).catch(next);\n };\n}\n\n/**\n * For RegExp-mounted (catch-all) routes, Express exposes captures as params[0..n].\n * Rename them to the segment names from the file path; catch-alls become string\n * arrays (`[...slug]` → `['a', 'b']`), absent optional segments become undefined.\n */\nfunction namedParams(route: RouteEntry): RequestHandler {\n const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\\*/g)].map((m) => m[1]!));\n return (req, _res, next) => {\n // 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 ...paramMapper,\n ...routeMiddlewares,\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: HttpMethod[] = [];\n const unimplemented: HttpMethod[] = [];\n\n for (const method of HTTP_METHODS) {\n if (typeof mod[method] === 'function') {\n implemented.push(method);\n const methodSchema = schemaFor(schema, method);\n const validation = methodSchema ? [validateRequest(methodSchema)] : [];\n app[method.toLowerCase() as Lowercase<HttpMethod>](\n routePath,\n httpOnly,\n ...paramMapper,\n ...routeMiddlewares,\n ...validation,\n asyncWrap(mod[method] as RequestHandler),\n );\n } else {\n unimplemented.push(method);\n }\n }\n\n if (implemented.length > 0 && unimplemented.length > 0) {\n const allowHeader = implemented.join(', ');\n app.all(routePath, (req, res, next) => {\n if (isUpgrade(req)) return next();\n if ((unimplemented as string[]).includes(req.method)) {\n res.set('Allow', allowHeader).status(405).json({ error: 'Method Not Allowed' });\n } else {\n next();\n }\n });\n }\n\n mounted.push({\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 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 { 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 app.use(requestLogger());\n\n if (config.requestTimeout) {\n const ms = config.requestTimeout;\n app.use((_req, res, next) => {\n const timer = setTimeout(() => {\n if (!res.headersSent) res.status(408).json({ error: 'Request Timeout', statusCode: 408 });\n }, ms);\n const clear = () => clearTimeout(timer);\n res.once('finish', clear);\n res.once('close', clear);\n next();\n });\n }\n\n const corsOption = config.cors ?? true;\n if (corsOption !== false) {\n const origin =\n typeof corsOption === 'object' && corsOption.origin !== undefined ? corsOption.origin : true;\n const corsOpts = typeof corsOption === 'object' ? { ...corsOption, origin } : { origin };\n app.use(cors(corsOpts));\n }\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n app.use(cookieParser());\n\n for (const mw of globalMiddlewares) {\n app.use(mw);\n }\n\n return app;\n}\n\nexport function mountErrorHandler(\n app: express.Express,\n onError?: express.ErrorRequestHandler,\n): void {\n if (onError) {\n app.use(onError);\n } else {\n app.use(\n (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {\n // e.g. a handler that kept going after requestTimeout already answered 408.\n if (res.headersSent) {\n getLogger().warn({ err }, 'Error after the response was sent');\n return;\n }\n // isHttpError() covers the common case, but errors can also arrive as plain\n // objects with a numeric statusCode (e.g. thrown across a module boundary, or\n // duck-typed by user code) — fall back to that shape before giving up to 500.\n // Only 4xx: a library's 5xx message can describe internals (hosts, SQL, paths).\n const status = (err as { statusCode?: unknown } | null)?.statusCode;\n const duckTyped =\n err instanceof Error && typeof status === 'number' && status >= 400 && status < 500\n ? (err as Error & { statusCode: number })\n : null;\n\n if (isHttpError(err)) {\n // ModelValidationError carries per-field issues; surface them like route validation does.\n const issues = (err as { issues?: unknown }).issues;\n res.status(err.statusCode).json({\n error: err.message,\n statusCode: err.statusCode,\n ...(issues !== undefined && { issues }),\n });\n } else if (duckTyped) {\n res\n .status(duckTyped.statusCode)\n .json({ error: duckTyped.message, statusCode: duckTyped.statusCode });\n } else {\n getLogger().error({ err }, 'Unhandled error');\n res.status(500).json({ error: 'Internal Server Error', statusCode: 500 });\n }\n },\n );\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-DTMDJGRW.cjs","../src/tasks/bullmq-backend.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACGA,IAAI,UAAA,EAA0C,IAAA;AAC9C,IAAI,gBAAA,EAAiC,OAAA,CAAQ,OAAA,CAAQ,CAAA;AAO9C,IAAM,iBAAA,EAAmB,WAAA;AAEhC,SAAS,UAAA,CAAW,GAAA,EAAqB;AACvC,EAAA,OAAO;AAAA;AAAA,IAEL,QAAA,EAAA,kBAAW,GAAA,CAAI,OAAA,CAAQ,OAAA,UAAW,GAAA,EAAA,EAAK,CAAA;AAAA,IACvC,OAAA,EAAS,EAAE,IAAA,mBAAM,GAAA,CAAI,OAAA,CAAQ,OAAA,UAAW,eAAA,EAAe,KAAA,EAAO,IAAK;AAAA,EACrE,CAAA;AACF;AAKA,MAAA,SAAe,aAAA,CAAc,KAAA,EAAsC;AACjE,EAAA,MAAM,OAAA,kBAAS,IAAI,GAAA,CAAY,CAAA;AAC/B,EAAA,IAAA,CAAA,MAAW,IAAA,GAAO,8BAAA,CAAa,MAAA,CAAO,CAAA,EAAG;AACvC,IAAA,GAAA,CAAI,CAAC,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,QAAA;AAC3B,IAAA,MAAM,GAAA,EAAK,iBAAA,EAAmB,GAAA,CAAI,IAAA;AAClC,IAAA,MAAA,CAAO,GAAA,CAAI,EAAE,CAAA;AACb,IAAA,MA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rB,IAAA;AACiD,MAAA;AACnD,MAAA;AACuD,QAAA;AACjE,MAAA;AACA,IAAA;AACkB,MAAA;AACpB,IAAA;AACD,EAAA;AAEa,EAAA;AAIc,EAAA;AAGiB,IAAA;AAC1C,EAAA;AAEqB,EAAA;AACZ,IAAA;AACS,IAAA;AACD,IAAA;AACpB,EAAA;AAE6C,EAAA;AAC/C;AAW4D;AACtD,EAAA;AACmB,IAAA;AACW,IAAA;AACV,MAAA;AACe,MAAA;AACrC,IAAA;AAC+D,IAAA;AACA,IAAA;AACpB,IAAA;AACR,IAAA;AACS,IAAA;AACrC,IAAA;AACD,EAAA;AACiC,IAAA;AACzC,EAAA;AACF;AD/CuE;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-DTMDJGRW.cjs","sourcesContent":[null,"import 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 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) },\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 queue = new bullmq.Queue(opts.queue, {\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 const def = taskRegistry.get(job.name);\n if (!def) {\n throw new Error(`[EFC] No task registered for name: ${job.name}`);\n }\n\n if (def.options.thread && def.filePath) {\n await runInThread(def.filePath, job.data);\n } else {\n await def.handler(job.data);\n }\n },\n { connection, concurrency: opts.concurrency },\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 const add = queue.waitUntilReady().then(() => queue.add(name, payload, jobOptions(def)));\n\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `[EFC] Cannot enqueue task \"${name}\": Redis at ${connection.host}:${connection.port} did not respond within ${opts.enqueueTimeout}ms`,\n ),\n ),\n opts.enqueueTimeout,\n );\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"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/tasks/pgboss-backend.ts"],"sourcesContent":["import type { PgBoss as PgBossType } from 'pg-boss';\nimport type { TaskDefinition } from '../types.js';\nimport { taskRegistry, setEnqueueImpl } from './index.js';\nimport { runInThread } from './thread-runner.js';\nimport { getLogger } from '../logger.js';\nimport { explainPostgresError } from '../db/postgres.js';\nimport type { FailedJob, TaskAdmin } from './admin.js';\n\n// pg-boss keeps one queue per job name, so each task gets its own pg-boss queue\n// named `<tasks.queue>.<TaskName>` — the prefix keeps apps sharing a database apart.\n\ninterface PgBossOpts {\n connectionString: string;\n concurrency: number;\n enqueueTimeout: number;\n queue: string;\n schema?: string;\n}\n\n// pg-boss payloads must be objects; other values are boxed so any enqueue() payload works.\nconst BOX = '__efcValue';\nconst box = (payload: unknown): object =>\n payload !== null && typeof payload === 'object' && !Array.isArray(payload)\n ? (payload as object)\n : { [BOX]: payload };\nconst unbox = (data: unknown): unknown =>\n data !== null && typeof data === 'object' && BOX in data\n ? (data as Record<string, unknown>)[BOX]\n : data;\n\nconst retryOptions = (def: TaskDefinition) => ({\n // pg-boss's retryLimit counts re-runs, exactly like EFC's `retries`.\n retryLimit: def.options.retries ?? 3,\n retryDelay: 1,\n retryBackoff: (def.options.backoff ?? 'exponential') === 'exponential',\n});\n\nasync function loadPgBoss(): Promise<typeof PgBossType> {\n try {\n const mod = (await import('pg-boss')) as unknown as {\n PgBoss?: typeof PgBossType;\n default?: typeof PgBossType | { PgBoss: typeof PgBossType };\n };\n const ctor =\n mod.PgBoss ??\n (typeof mod.default === 'function'\n ? mod.default\n : (mod.default as { PgBoss: typeof PgBossType }).PgBoss);\n return ctor;\n } catch {\n throw new Error('[EFC] pg-boss is not installed. Run: npm install pg-boss');\n }\n}\n\nlet closeImpl: (() => Promise<void>) | null = null;\n\nexport async function closePgBoss(): Promise<void> {\n const close = closeImpl;\n closeImpl = null;\n await close?.();\n}\n\nexport async function initPgBoss(opts: PgBossOpts): Promise<void> {\n const PgBoss = await loadPgBoss();\n const boss = new PgBoss({\n connectionString: opts.connectionString,\n ...(opts.schema !== undefined && { schema: opts.schema }),\n });\n boss.on('error', (err: Error) => getLogger().error({ err }, 'pg-boss error'));\n try {\n await boss.start();\n } catch (err) {\n throw explainPostgresError(err, opts.connectionString);\n }\n\n const queueFor = (name: string) => `${opts.queue}.${name}`;\n const wantedSchedules = new Set<string>();\n\n for (const def of taskRegistry.values()) {\n const queue = queueFor(def.name);\n await boss.createQueue(queue, retryOptions(def));\n await boss.work(\n queue,\n { localConcurrency: def.options.concurrency ?? opts.concurrency },\n async (jobs: { id: string; data: unknown; retryCount: number }[]) => {\n for (const job of jobs) {\n const payload = unbox(job.data);\n try {\n if (def.options.thread && def.filePath) await runInThread(def.filePath, payload);\n else await def.handler(payload);\n getLogger().info({ task: def.name, jobId: job.id }, `Task ${def.name} completed`);\n } catch (err) {\n getLogger().error(\n { task: def.name, jobId: job.id, attempt: job.retryCount + 1, err },\n `Task ${def.name} failed`,\n );\n throw err;\n }\n }\n },\n );\n if (def.options.schedule) {\n wantedSchedules.add(queue);\n await boss.schedule(\n queue,\n def.options.schedule,\n {},\n {\n ...retryOptions(def),\n ...(def.options.timezone !== undefined && { tz: def.options.timezone }),\n },\n );\n }\n }\n\n // Drop schedules for tasks that lost their `schedule` or no longer exist.\n for (const s of await boss.getSchedules()) {\n if (s.name.startsWith(`${opts.queue}.`) && !wantedSchedules.has(s.name)) {\n await boss.unschedule(s.name);\n }\n }\n if (wantedSchedules.size > 0) getLogger().info(`Scheduled ${wantedSchedules.size} cron task(s)`);\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 let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `[EFC] Cannot enqueue task \"${name}\": PostgreSQL did not respond within ${opts.enqueueTimeout}ms`,\n ),\n ),\n opts.enqueueTimeout,\n );\n });\n try {\n await Promise.race([boss.send(queueFor(name), box(payload), retryOptions(def)), 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 closeImpl = async () => {\n // graceful: lets in-flight jobs finish before the connection pool closes.\n await boss.stop({ graceful: true, timeout: 10_000 });\n };\n\n getLogger().info('pg-boss backend initialised');\n}\n\n/** Dead-letter inspection for `efc tasks failed | retry | purge` on pg-boss. */\nexport async function pgBossAdmin(\n connectionString: string,\n queue = 'efc',\n schema = 'pgboss',\n): Promise<TaskAdmin> {\n const PgBoss = await loadPgBoss();\n // No supervision or cron here: this instance only reads and settles jobs.\n const boss = new PgBoss({\n connectionString,\n schema,\n supervise: false,\n schedule: false,\n migrate: false,\n });\n boss.on('error', () => {});\n await boss.start();\n const db = boss.getDb();\n const prefix = `${queue}.`;\n const taskOf = (name: string) => name.slice(prefix.length);\n const table = `\"${schema.replace(/\"/g, '\"\"')}\".job`;\n\n const failedRows = async (ids: string[], limit = 10_000) =>\n (\n await db.executeSql(\n `SELECT id, name, data, output, retry_count, completed_on FROM ${table}\n WHERE state = 'failed' AND starts_with(name, $1) ${ids.length ? 'AND id = ANY($3::uuid[])' : ''}\n ORDER BY completed_on DESC NULLS LAST LIMIT $2`,\n ids.length ? [prefix, limit, ids] : [prefix, limit],\n )\n ).rows as {\n id: string;\n name: string;\n data: unknown;\n output: unknown;\n retry_count: number;\n completed_on: Date | null;\n }[];\n\n const byQueue = (rows: { id: string; name: string }[]) => {\n const groups = new Map<string, string[]>();\n for (const r of rows) groups.set(r.name, [...(groups.get(r.name) ?? []), r.id]);\n return groups;\n };\n\n return {\n async counts() {\n const { rows } = await db.executeSql(\n `SELECT state, count(*)::int AS n FROM ${table} WHERE starts_with(name, $1) GROUP BY state`,\n [prefix],\n );\n return Object.fromEntries(\n (rows as { state: string; n: number }[]).map((r) => [r.state, r.n]),\n );\n },\n async listFailed({ limit, name }) {\n const rows = (await failedRows([], name ? 10_000 : limit)).filter(\n (r) => !name || taskOf(r.name) === name,\n );\n return rows.slice(0, limit).map(\n (r): FailedJob => ({\n id: r.id,\n name: taskOf(r.name),\n data: unbox(r.data),\n error: String((r.output as { message?: string } | null)?.message ?? r.output ?? ''),\n attempts: r.retry_count + 1,\n failedAt: r.completed_on ?? undefined,\n }),\n );\n },\n async retry(ids) {\n const rows = await failedRows(ids);\n for (const [q, list] of byQueue(rows)) await boss.retry(q, list);\n return rows.length;\n },\n async purge(ids) {\n const rows = await failedRows(ids);\n for (const [q, list] of byQueue(rows)) await boss.deleteJob(q, list);\n return rows.length;\n },\n async close() {\n await boss.stop({ graceful: false });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,IAAM,MAAM;AACZ,IAAM,MAAM,CAAC,YACX,YAAY,QAAQ,OAAO,YAAY,YAAY,CAAC,MAAM,QAAQ,OAAO,IACpE,UACD,EAAE,CAAC,GAAG,GAAG,QAAQ;AACvB,IAAM,QAAQ,CAAC,SACb,SAAS,QAAQ,OAAO,SAAS,YAAY,OAAO,OAC/C,KAAiC,GAAG,IACrC;AAEN,IAAM,eAAe,CAAC,SAAyB;AAAA;AAAA,EAE7C,YAAY,IAAI,QAAQ,WAAW;AAAA,EACnC,YAAY;AAAA,EACZ,eAAe,IAAI,QAAQ,WAAW,mBAAmB;AAC3D;AAEA,eAAe,aAAyC;AACtD,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AAInC,UAAM,OACJ,IAAI,WACH,OAAO,IAAI,YAAY,aACpB,IAAI,UACH,IAAI,QAA0C;AACrD,WAAO;AAAA,EACT,QAAQ;AACN,UAAM,IAAI,MAAM,0DAA0D;AAA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;AACgB,MAAA;AAC8B,QAAA;AACzB,UAAA;AACR,YAAA;AACmB,YAAA;AAC3B,UAAA;AAC6C,UAAA;AAChD,QAAA;AACF,MAAA;AAEa,MAAA;AACwB,QAAA;AAC7B,UAAA;AACmB,YAAA;AACT,UAAA;AACF,YAAA;AAC8B,cAAA;AAAiD,EAAA;AACzF,YAAA;AACF,UAAA;AACF,QAAA;AACF,MAAA;AAC+C,MAAA;AAClB,MAAA;AAChB,MAAA;AACiC,QAAA;AACtC,UAAA;AAC8B,YAAA;AAC1B,UAAA;AAGG,YAAA;AAEG,YAAA;AACoC,cAAA;AACrB,cAAA;AAC3B,YAAA;AACF,UAAA;AACF,QAAA;AACF,MAAA;AAG8B,MAAA;AAClB,IAAA;AAC6B,MAAA;AAAE,MAAA;AACrC,MAAA;AACN,IAAA;AACa,MAAA;AACf,IAAA;AACF,EAAA;AAEsB,EAAA;AACU,IAAA;AACyB,IAAA;AACjB,IAAA;AACxC,EAAA;AAEO,EAAA;AACL,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACF;AHgF4D;AACA;AACA;AACA;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-GWMW6XY7.cjs","sourcesContent":[null,"import { randomBytes, randomUUID } from 'node:crypto';\nimport type {\n DefaultOperator,\n CollectionPrimitiveFieldType,\n CollectionSchema,\n ModelSchema,\n ModelOptions,\n TableFieldDefinition,\n TablePrimitiveFieldType,\n TableSchema,\n TableSchemaField,\n} from '../types.js';\nimport { getCurrentUser } from '../context.js';\nimport { HttpError } from '../errors.js';\n\n// ── Normalised schema tree ───────────────────────────────────────────────────\n// The three accepted field syntaxes (FieldDefinition, nested-schema shorthand,\n// [schema] tuple) collapse into one tree that the engine adapters walk. The tree\n// covers defineTable's SQL types too; defineModel schemas just never contain them.\n\nexport type ScalarType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'date'\n | 'objectId'\n | 'integer'\n | 'bigint'\n | 'decimal'\n | 'uuid'\n | 'decimal128'\n | 'long'\n | 'geoPoint'\n | 'binary';\n\n/** Every field definition the tree holds (a superset of the portable `FieldDefinition`). */\nexport type AnyFieldDefinition = Omit<TableFieldDefinition, 'type' | 'index'> & {\n type: TablePrimitiveFieldType | CollectionPrimitiveFieldType | 'array';\n index?: boolean | '2dsphere' | 'text' | 'hashed';\n};\n\nexport type FieldNode =\n | { kind: 'scalar'; type: ScalarType; def: AnyFieldDefinition }\n | { kind: 'json'; def: AnyFieldDefinition } // untyped object / untyped array / json\n | { kind: 'object'; fields: SchemaTree; def: AnyFieldDefinition }\n | { kind: 'array'; item: FieldNode; def: AnyFieldDefinition };\n\nexport type SchemaTree = Record<string, FieldNode>;\n\n/** Which model API a schema belongs to — it decides the field types allowed. */\nexport type SchemaMode = 'model' | 'table' | 'collection';\n\nconst MODEL_TYPES = new Set(['string', 'number', 'boolean', 'date', 'object', 'objectId', 'array']);\nconst TABLE_ONLY_TYPES = new Set(['integer', 'bigint', 'decimal', 'uuid', 'json']);\nconst COLLECTION_ONLY_TYPES = new Set(['decimal128', 'long', 'geoPoint', 'binary']);\nconst SPECIAL_INDEXES = new Set(['2dsphere', 'text', 'hashed']);\nconst TABLE_ONLY_OPTIONS = ['precision', 'scale', 'nativeEnum', 'column', 'onDelete'] as const;\nconst REFERENTIAL_ACTIONS = new Set(['restrict', 'cascade', 'setNull']);\nconst FOREIGN_KEY_TYPES = new Set(['objectId', 'uuid', 'integer', 'bigint']);\n\nexport function isFieldDefinition(value: unknown): value is AnyFieldDefinition {\n if (value == null || typeof value !== 'object' || Array.isArray(value)) return false;\n const type = (value as { type?: unknown }).type;\n return (\n typeof type === 'string' &&\n (MODEL_TYPES.has(type) || TABLE_ONLY_TYPES.has(type) || COLLECTION_ONLY_TYPES.has(type))\n );\n}\n\nconst untyped = (): FieldNode => ({ kind: 'json', def: { type: 'object' } });\n\nclass SchemaBuilder {\n constructor(\n private readonly model: string,\n private readonly mode: SchemaMode,\n ) {}\n\n private fail(path: string, message: string): never {\n throw new Error(`[EFC] ${this.model}.${path}: ${message}`);\n }\n\n private checkType(type: string, path: string) {\n if (this.mode !== 'table' && TABLE_ONLY_TYPES.has(type)) {\n this.fail(path, `type '${type}' is PostgreSQL-only — use defineTable, or a portable type`);\n }\n if (this.mode !== 'collection' && COLLECTION_ONLY_TYPES.has(type)) {\n this.fail(path, `type '${type}' is MongoDB-only — use defineCollection, or a portable type`);\n }\n }\n\n private checkDefinition(def: AnyFieldDefinition, path: string, topLevel: boolean) {\n this.checkType(def.type, path);\n if (def.renamedFrom !== undefined && !topLevel) {\n this.fail(path, `'renamedFrom' only applies to top-level fields`);\n }\n const index = def.index as unknown;\n if (typeof index === 'string' && (this.mode !== 'collection' || !SPECIAL_INDEXES.has(index))) {\n this.fail(\n path,\n `index must be true or false${this.mode === 'collection' ? `, '2dsphere', 'text' or 'hashed'` : ''}`,\n );\n }\n if (this.mode !== 'table') {\n for (const opt of TABLE_ONLY_OPTIONS) {\n if (def[opt] !== undefined) this.fail(path, `'${opt}' is a defineTable option`);\n }\n return;\n }\n if ((def.precision !== undefined || def.scale !== undefined) && def.type !== 'decimal') {\n this.fail(path, `'precision' / 'scale' only apply to decimal fields`);\n }\n if (def.scale !== undefined && def.precision === undefined) {\n this.fail(path, `'scale' needs 'precision'`);\n }\n if (def.nativeEnum && !(def.enum && def.enum.every((v) => typeof v === 'string'))) {\n this.fail(path, `'nativeEnum' needs a string 'enum'`);\n }\n if (def.column !== undefined && !topLevel) {\n this.fail(path, `'column' only applies to top-level fields`);\n }\n if (def.onDelete !== undefined) {\n if (def.ref === undefined) this.fail(path, `'onDelete' needs 'ref'`);\n if (!REFERENTIAL_ACTIONS.has(def.onDelete)) {\n this.fail(path, `onDelete must be 'restrict', 'cascade' or 'setNull'`);\n }\n if (def.onDelete === 'setNull' && def.required) {\n this.fail(path, `onDelete: 'setNull' can't clear a required field`);\n }\n }\n // A scalar ref is a foreign key, an array of refs a many-to-many join table: both\n // top-level and typed like the target's id.\n if (def.ref !== undefined) {\n const many = def.type === 'array';\n if (!topLevel) this.fail(path, `'ref' only applies to top-level fields`);\n if (!FOREIGN_KEY_TYPES.has(many ? String(def.of) : def.type)) {\n this.fail(\n path,\n many\n ? `a many-to-many 'ref' needs of: objectId, uuid, integer or bigint`\n : `'ref' needs an id type: objectId, uuid, integer or bigint`,\n );\n }\n if (many && def.onDelete !== undefined) {\n this.fail(\n path,\n `'onDelete' doesn't apply to many-to-many refs — links are always removed with either record`,\n );\n }\n if (many && (def.unique || def.index)) {\n this.fail(path, `many-to-many refs are indexed already; 'unique' / 'index' don't apply`);\n }\n }\n }\n\n private item(of: AnyFieldDefinition['of'], parent: AnyFieldDefinition, path: string): FieldNode {\n if (of === undefined) return untyped();\n if (typeof of === 'string') {\n this.checkType(of, path);\n if (of === 'object' || of === 'json') return untyped();\n const def: AnyFieldDefinition = {\n type: of,\n ...(parent.ref !== undefined && { ref: parent.ref }),\n };\n return { kind: 'scalar', type: of, def };\n }\n return { kind: 'object', fields: this.tree(of, `${path}.$`), def: { type: 'object' } };\n }\n\n field(field: TableSchemaField, path: string, topLevel: boolean): FieldNode {\n if (Array.isArray(field)) {\n const inner = (field as readonly TableSchema[])[0];\n return {\n kind: 'array',\n item: inner\n ? { kind: 'object', fields: this.tree(inner, `${path}.$`), def: { type: 'object' } }\n : untyped(),\n def: { type: 'array' },\n };\n }\n if (!isFieldDefinition(field)) {\n const type = (field as { type?: unknown }).type;\n if (typeof type === 'string') this.fail(path, `unknown field type '${type}'`);\n return {\n kind: 'object',\n fields: this.tree(field as TableSchema, path),\n def: { type: 'object' },\n };\n }\n const def = field;\n this.checkDefinition(def, path, topLevel);\n if (def.type === 'array') return { kind: 'array', item: this.item(def.of, def, path), def };\n if (def.type === 'object') {\n return def.fields\n ? { kind: 'object', fields: this.tree(def.fields, path), def }\n : { kind: 'json', def };\n }\n if (def.type === 'json') return { kind: 'json', def };\n return { kind: 'scalar', type: def.type, def };\n }\n\n tree(schema: TableSchema, prefix = ''): SchemaTree {\n const out: SchemaTree = {};\n for (const [key, field] of Object.entries(schema)) {\n out[key] = this.field(field, prefix ? `${prefix}.${key}` : key, prefix === '');\n }\n return out;\n }\n}\n\n/**\n * Normalises a schema. `model` mode (defineModel) rejects the PostgreSQL-only types and\n * options with an `[EFC]` error naming the field; `table` mode (defineTable) accepts them.\n */\nexport function normalizeSchema(\n schema: ModelSchema | TableSchema | CollectionSchema,\n mode: SchemaMode = 'model',\n model = 'Model',\n): SchemaTree {\n return new SchemaBuilder(model, mode).tree(schema as TableSchema);\n}\n\nexport function timestampFields(options: ModelOptions): { createdAt?: string; updatedAt?: string } {\n const ts = options.timestamps ?? true;\n if (ts === false) return {};\n if (ts === true) return { createdAt: 'createdAt', updatedAt: 'updatedAt' };\n const out: { createdAt?: string; updatedAt?: string } = {};\n if (ts.createdAt !== false) out.createdAt = ts.createdAt ?? 'createdAt';\n if (ts.updatedAt !== false) out.updatedAt = ts.updatedAt ?? 'updatedAt';\n return out;\n}\n\n// ── Default operator codes ───────────────────────────────────────────────────\n\nconst STATIC_DEFAULT_OPERATORS: Record<string, () => unknown> = {\n $now: () => new Date(),\n $uuid: () => randomUUID(),\n $timestamp: () => Date.now(),\n $shortId: () => randomBytes(12).toString('base64url'),\n};\n\nconst FIXED_DEFAULT_OPERATORS = new Set(['$now', '$uuid', '$objectId', '$timestamp', '$shortId']);\n\nfunction isCurrentUserOperator(value: unknown): value is '$currentUser' | `$currentUser.${string}` {\n return (\n typeof value === 'string' && (value === '$currentUser' || value.startsWith('$currentUser.'))\n );\n}\n\nexport function isDefaultOperator(value: unknown): value is DefaultOperator {\n return (\n (typeof value === 'string' && FIXED_DEFAULT_OPERATORS.has(value)) ||\n isCurrentUserOperator(value)\n );\n}\n\n/**\n * Turns a `default` into something evaluated per record: operator codes become\n * generator functions (so each insert — or, for `$currentUser`, each request — gets a\n * fresh value), functions pass through, literals are returned as-is. `objectId` is the\n * engine's id generator (mongoose ObjectId, or a UUID on PostgreSQL).\n */\nexport function resolveDefault(value: unknown, objectId: () => unknown): unknown {\n if (!isDefaultOperator(value)) return value;\n if (value === '$objectId') return objectId;\n if (value === '$currentUser') return () => getCurrentUser();\n if (isCurrentUserOperator(value)) {\n const key = value.slice('$currentUser.'.length);\n return () => getCurrentUser()?.[key];\n }\n return STATIC_DEFAULT_OPERATORS[value];\n}\n\n/** Applies defaults for missing top-level fields and nested object fields (PostgreSQL path). */\nexport function applyDefaults(\n tree: SchemaTree,\n data: Record<string, unknown>,\n objectId: () => unknown,\n): Record<string, unknown> {\n const out: Record<string, unknown> = { ...data };\n for (const [key, node] of Object.entries(tree)) {\n if (out[key] === undefined && node.def.default !== undefined) {\n const d = resolveDefault(node.def.default, objectId);\n const value = typeof d === 'function' ? (d as () => unknown)() : structuredClone(d);\n if (value !== undefined) out[key] = value;\n }\n if (node.kind === 'object' && out[key] != null && typeof out[key] === 'object') {\n out[key] = applyDefaults(node.fields, out[key] as Record<string, unknown>, objectId);\n }\n if (node.kind === 'array' && node.item.kind === 'object' && Array.isArray(out[key])) {\n const fields = node.item.fields;\n out[key] = (out[key] as unknown[]).map((v) =>\n v != null && typeof v === 'object'\n ? applyDefaults(fields, v as Record<string, unknown>, objectId)\n : v,\n );\n }\n }\n return out;\n}\n\n// ── Validation ───────────────────────────────────────────────────────────────\n\nexport interface FieldIssue {\n path: string;\n message: string;\n}\n\n/** Thrown by every model write that fails validation, on either engine. → HTTP 400. */\nexport class ModelValidationError extends HttpError {\n readonly issues: FieldIssue[];\n\n constructor(model: string, issues: FieldIssue[]) {\n super(\n 400,\n `${model} validation failed: ${issues.map((i) => `${i.path}: ${i.message}`).join('; ')}`,\n );\n this.name = 'ModelValidationError';\n this.issues = issues;\n }\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst INT4 = 2 ** 31;\nconst INT8_MIN = -(2n ** 63n);\nconst INT8_MAX = 2n ** 63n - 1n;\nconst DECIMAL_RE = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)$/;\n\n/** Digits before / after the point of a decimal string or number. */\nfunction decimalDigits(value: string | number): { int: number; frac: number } {\n const str = typeof value === 'number' ? String(value) : value;\n const [i = '', f = ''] = str.replace(/^[+-]/, '').split('.');\n return { int: i.replace(/^0+/, '').length, frac: f.replace(/0+$/, '').length };\n}\n\nfunction typeError(type: ScalarType, def: AnyFieldDefinition, value: unknown): string | null {\n switch (type) {\n case 'string':\n return typeof value === 'string' ? null : 'must be a string';\n case 'number':\n return typeof value === 'number' && Number.isFinite(value) ? null : 'must be a number';\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value) && value >= -INT4 && value < INT4\n ? null\n : 'must be a 32-bit integer';\n case 'bigint': {\n const big =\n typeof value === 'bigint'\n ? value\n : typeof value === 'number' && Number.isSafeInteger(value)\n ? BigInt(value)\n : undefined;\n return big !== undefined && big >= INT8_MIN && big <= INT8_MAX\n ? null\n : 'must be a 64-bit integer (bigint)';\n }\n case 'decimal': {\n const ok =\n (typeof value === 'number' && Number.isFinite(value)) ||\n (typeof value === 'string' && DECIMAL_RE.test(value));\n if (!ok) return 'must be a decimal number or numeric string';\n if (def.precision !== undefined) {\n const scale = def.scale ?? 0;\n const { int, frac } = decimalDigits(value as string | number);\n if (frac > scale) return `must have at most ${scale} decimal places`;\n if (int > def.precision - scale)\n return `must have at most ${def.precision - scale} digits before the decimal point`;\n }\n return null;\n }\n case 'boolean':\n return typeof value === 'boolean' ? null : 'must be a boolean';\n case 'date':\n return !Number.isNaN(new Date(value as string | number | Date).getTime())\n ? null\n : 'must be a date';\n case 'objectId':\n return typeof value === 'string' && UUID_RE.test(value) ? null : 'must be a valid id';\n case 'uuid':\n return typeof value === 'string' && UUID_RE.test(value) ? null : 'must be a UUID';\n case 'decimal128':\n case 'long':\n case 'geoPoint':\n case 'binary':\n return null; // defineCollection only: mongoose casts and validates these\n }\n}\n\ntype Bound = number | bigint | string | Date;\n\n/** < 0 / 0 / > 0 comparing a (type-checked) value with a min/max bound. */\nfunction compareBound(def: AnyFieldDefinition, value: unknown, bound: Bound): number {\n if (def.type === 'bigint') {\n const a = BigInt(value as bigint | number);\n const b = BigInt(bound instanceof Date ? bound.getTime() : bound);\n return a < b ? -1 : a > b ? 1 : 0;\n }\n const num = (v: unknown) =>\n v instanceof Date\n ? v.getTime()\n : def.type === 'date'\n ? new Date(v as string | number).getTime()\n : Number(v);\n return num(value) - num(bound);\n}\n\nasync function checkRules(\n def: AnyFieldDefinition,\n value: unknown,\n path: string,\n issues: FieldIssue[],\n) {\n if (def.enum && !def.enum.includes(value as string | number)) {\n issues.push({ path, message: `must be one of: ${def.enum.join(', ')}` });\n }\n const ordered =\n typeof value === 'number' ||\n typeof value === 'bigint' ||\n value instanceof Date ||\n def.type === 'date' ||\n (def.type === 'decimal' && typeof value === 'string');\n if (ordered) {\n if (def.min !== undefined && compareBound(def, value, def.min) < 0)\n issues.push({ path, message: `must be >= ${String(def.min)}` });\n if (def.max !== undefined && compareBound(def, value, def.max) > 0)\n issues.push({ path, message: `must be <= ${String(def.max)}` });\n }\n if (typeof value === 'string' && def.type !== 'decimal') {\n if (def.minLength !== undefined && value.length < def.minLength)\n issues.push({ path, message: `must be at least ${def.minLength} characters` });\n if (def.maxLength !== undefined && value.length > def.maxLength)\n issues.push({ path, message: `must be at most ${def.maxLength} characters` });\n if (def.match && !def.match.test(value))\n issues.push({ path, message: `must match ${String(def.match)}` });\n }\n if (def.validate) {\n const result = await def.validate(value);\n if (result !== true)\n issues.push({ path, message: typeof result === 'string' ? result : 'is invalid' });\n }\n}\n\nasync function validateNode(\n node: FieldNode,\n value: unknown,\n path: string,\n issues: FieldIssue[],\n partial: boolean,\n) {\n if (value === undefined || value === null) {\n if (node.def.required && !partial) issues.push({ path, message: 'is required' });\n if (node.def.required && partial && value === null)\n issues.push({ path, message: 'is required' });\n return;\n }\n switch (node.kind) {\n case 'scalar': {\n const err = typeError(node.type, node.def, value);\n if (err) {\n issues.push({ path, message: err });\n return;\n }\n await checkRules(node.def, value, path, issues);\n return;\n }\n case 'json':\n await checkRules(node.def, value, path, issues);\n return;\n case 'object':\n if (typeof value !== 'object' || Array.isArray(value)) {\n issues.push({ path, message: 'must be an object' });\n return;\n }\n await validateTree(node.fields, value as Record<string, unknown>, issues, false, path);\n await checkRules(node.def, value, path, issues);\n return;\n case 'array':\n if (!Array.isArray(value)) {\n issues.push({ path, message: 'must be an array' });\n return;\n }\n for (let i = 0; i < value.length; i++) {\n await validateNode(\n { ...node.item, def: { ...node.item.def, required: true } } as FieldNode,\n value[i],\n `${path}.${i}`,\n issues,\n false,\n );\n }\n await checkRules(node.def, value, path, issues);\n }\n}\n\n/**\n * Validates `data` against the tree. `partial` (updates) only checks fields present in\n * `data`, but still rejects explicitly nulling a required field.\n */\nexport async function validateTree(\n tree: SchemaTree,\n data: Record<string, unknown>,\n issues: FieldIssue[],\n partial: boolean,\n prefix = '',\n): Promise<FieldIssue[]> {\n for (const [key, node] of Object.entries(tree)) {\n if (partial && !(key in data)) continue;\n await validateNode(node, data[key], prefix ? `${prefix}.${key}` : key, issues, partial);\n }\n return issues;\n}\n\n/** Fields declared with `ref` (top-level objectId or objectId arrays) → referenced model name. */\nexport function refFields(tree: SchemaTree): Map<string, { model: string; many: boolean }> {\n const refs = new Map<string, { model: string; many: boolean }>();\n for (const [key, node] of Object.entries(tree)) {\n if (node.kind === 'scalar' && node.type === 'objectId' && node.def.ref) {\n refs.set(key, { model: node.def.ref, many: false });\n } else if (\n node.kind === 'array' &&\n node.item.kind === 'scalar' &&\n node.item.type === 'objectId' &&\n node.def.ref\n ) {\n refs.set(key, { model: node.def.ref, many: true });\n }\n }\n return refs;\n}\n\nexport function sequenceFields(name: string, tree: SchemaTree): { path: string; key: string }[] {\n const out: { path: string; key: string }[] = [];\n for (const [path, node] of Object.entries(tree)) {\n if (node.def.sequence) {\n out.push({\n path,\n key: typeof node.def.sequence === 'string' ? node.def.sequence : `${name}.${path}`,\n });\n }\n }\n return out;\n}\n\n/** The schema node a dotted path points at (`meta.counts.views`, `items.0.sku`), if any. */\nexport function nodeAt(tree: SchemaTree, path: string[]): FieldNode | undefined {\n let node: FieldNode | undefined = tree[path[0]!];\n for (const part of path.slice(1)) {\n if (!node) return undefined;\n if (node.kind === 'object') node = node.fields[part];\n else if (node.kind === 'array' && /^\\d+$/.test(part)) node = node.item;\n else if (node.kind === 'json')\n return node; // untyped JSON: anything goes below here\n else return undefined;\n }\n return node;\n}\n\n/** Validates one value written to a dotted path (partial-update rules). */\nexport async function validateAtPath(\n tree: SchemaTree,\n dotted: string,\n value: unknown,\n issues: FieldIssue[],\n): Promise<void> {\n const node = nodeAt(tree, dotted.split('.'));\n if (!node) {\n issues.push({ path: dotted, message: 'unknown field' });\n return;\n }\n await validateNode(node, value, dotted, issues, true);\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DatabaseEngine } from '../types.js';\n\n// Which adapter defineModel() compiles to. Set during Pre-Flight from\n// config.database / the DATABASE_URL scheme; MongoDB until then, which keeps code\n// that connects mongoose itself (tests, scripts) working without ignite().\nlet engine: DatabaseEngine | undefined;\n\nexport function setDbEngine(value: DatabaseEngine): void {\n engine = value;\n}\n\nexport function getDbEngine(): DatabaseEngine {\n return engine ?? 'mongodb';\n}\n\n// Whether models reconcile their table/collection on first use (EFCConfig.autoSync).\nlet autoSync = true;\n\nexport function setAutoSync(value: boolean): void {\n autoSync = value;\n}\n\nexport function isAutoSync(): boolean {\n return autoSync;\n}\n\n// Set while `efc db generate` replays migrations into its shadow schema: a migration that\n// calls `Model.sync()` (the scaffolded init migration does) mirrors the models as they are\n// *now*, which would hide every change from the diff — so those calls do nothing there.\nlet syncSuppressed = false;\n\nexport function setSyncSuppressed(value: boolean): void {\n syncSuppressed = value;\n}\n\nexport function isSyncSuppressed(): boolean {\n return syncSuppressed;\n}\n\n/** One step of a generated migration. */\nexport interface PlanStep {\n /**\n * PostgreSQL: a SQL statement. MongoDB: a JavaScript statement run against `db` (the\n * mongoose Connection). With `check`, a query returning `n` that must be 0.\n */\n sql: string;\n /** Best-effort reverse, for the migration's `down()`; `''` = nothing to undo. */\n down?: string;\n /** PostgreSQL: skip `sql` when this query returns a row (already applied). */\n skipIf?: string;\n /** `sql` counts offending rows: the migration stops with this message (`%n` = count). */\n check?: string;\n /** Foreign keys run after every table exists. */\n phase: 'main' | 'fk';\n}\n\n/** The explicit, possibly lossy extras `efc db generate` may add to the sync plan. */\nexport interface PlanOptions {\n /** Drop columns the model no longer declares. */\n allowDrop?: boolean;\n /** Add NOT NULL for required fields and validate enum checks, behind row checks. */\n tighten?: boolean;\n}\n\n/** What every model API (defineModel, defineTable) registers about itself. */\nexport interface RegisteredModel {\n readonly name: string;\n sync(options?: { dryRun?: boolean }): Promise<string[]>;\n /** The migration steps that would bring the database in line with the model. */\n plan?(options?: PlanOptions): Promise<PlanStep[]>;\n drop(): Promise<void>;\n /** Records by id — what `populate` needs from a `ref` target. */\n findByIds(ids: unknown[]): Promise<Record<string, unknown>[]>;\n /** PostgreSQL: its table and id strategy — what a foreign key to it needs. */\n pgTarget?(): { table: string; idKind: 'uuid' | 'serial' | 'bigserial' };\n /** defineTable only: its runtime, for `include` from other tables. */\n tableRuntime?(): unknown;\n /** `efc db studio --write`: where it stores, and writes through the model (validated). */\n studio?: StudioWriter;\n}\n\nexport interface StudioWriter {\n /** The table (PostgreSQL) or collection (MongoDB) its records live in. */\n storage(): Promise<string>;\n create(data: Record<string, unknown>): Promise<unknown>;\n /** `id` as it appears in the URL; the model converts it. */\n update(id: string, data: Record<string, unknown>): Promise<unknown>;\n delete(id: string): Promise<unknown>;\n}\n\n// Every defined model by name, so `populate` can resolve a `ref` on either engine\n// and `efc db` commands can sync everything that was imported.\nconst registry = new Map<string, RegisteredModel>();\n\nexport function registerModel(model: RegisteredModel): void {\n registry.set(model.name, model);\n}\n\nexport function getRegisteredModel(name: string): RegisteredModel | undefined {\n return registry.get(name);\n}\n\nexport function registeredModels(): RegisteredModel[] {\n return [...registry.values()];\n}\n\n// ── Transactions ─────────────────────────────────────────────────────────────\n\n/** The open transaction for the current async scope: a mongoose session or a Drizzle tx. */\nexport type TxHandle =\n | { engine: 'mongodb'; session: unknown }\n | {\n engine: 'postgresql';\n tx: unknown;\n /** Work to run once the transaction has committed (e.g. deferred foreign keys). */\n afterCommit: (() => void)[];\n };\n\nconst txStorage = new AsyncLocalStorage<TxHandle>();\n\nexport function currentTx(): TxHandle | undefined {\n return txStorage.getStore();\n}\n\nexport function runInTx<T>(handle: TxHandle, fn: () => Promise<T>): Promise<T> {\n return txStorage.run(handle, fn);\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any -- drizzle is an optional peer, loaded dynamically */\n// The PostgreSQL table behind a model: columns, the Drizzle table, schema sync, record\n// conversion, insert preparation, validation and error mapping. Shared by both query\n// layers on top of it — defineModel's MongoDB-style API (pg-model.ts) and defineTable's\n// Prisma-style API (table-model.ts) — so the same table reads and writes the same records.\nimport { randomUUID } from 'node:crypto';\nimport type { ModelOptions, ReferentialAction, TableOptions } from '../types.js';\nimport { HttpError } from '../errors.js';\nimport {\n applyDefaults,\n ModelValidationError,\n refFields,\n sequenceFields,\n timestampFields,\n validateTree,\n type AnyFieldDefinition,\n type FieldIssue,\n type FieldNode,\n type ScalarType,\n type SchemaTree,\n} from './schema.js';\nimport {\n currentTx,\n getRegisteredModel,\n isAutoSync,\n isSyncSuppressed,\n registeredModels,\n type PlanOptions,\n type PlanStep,\n} from './engine.js';\nimport { getOrm, getPool } from './postgres.js';\nimport { invalidatePreparedStatements } from './prepared-statements.js';\nimport { getLogger } from '../logger.js';\n\ntype AnyRecord = Record<string, unknown>;\n\ninterface Drizzle {\n sql: any;\n pgCore: any;\n}\n\nlet drizzlePromise: Promise<Drizzle> | undefined;\n\nexport function loadDrizzle(): Promise<Drizzle> {\n drizzlePromise ??= Promise.all([import('drizzle-orm'), import('drizzle-orm/pg-core')])\n .then(([orm, pgCore]) => ({ sql: (orm as any).sql, pgCore }))\n .catch(() => {\n drizzlePromise = undefined;\n throw new Error('[EFC] drizzle-orm is not installed. Run: npm install pg drizzle-orm');\n });\n return drizzlePromise;\n}\n\n/** mongoose-style collection naming so both engines agree: User → users, Category → categories. */\nexport function tableNameFor(model: string): string {\n const lower = model.toLowerCase();\n if (/[^aeiou]y$/.test(lower)) return lower.slice(0, -1) + 'ies';\n if (/(s|x|z|ch|sh)$/.test(lower)) return lower + 'es';\n return lower + 's';\n}\n\nexport const snakeCase = (s: string) =>\n s\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')\n .toLowerCase();\n\nexport const q = (ident: string) => `\"${ident.replace(/\"/g, '\"\"')}\"`;\nconst sequenceName = (key: string) => `efc_seq_${key.replace(/[^A-Za-z0-9_]/g, '_').toLowerCase()}`;\nconst literal = (v: string | number) =>\n typeof v === 'number' ? String(v) : `'${v.replace(/'/g, \"''\")}'`;\n\n// Tables whose sync is running in this process, so a foreign key to one of them can wait\n// for it instead of syncing it again (A ↔ B references would otherwise recurse).\nconst syncing = new Map<string, Promise<unknown>>();\n\nconst ACTION_SQL: Record<ReferentialAction, string> = {\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n};\n// pg_constraint.confdeltype\nconst ACTION_CODE: Record<ReferentialAction, string> = {\n restrict: 'r',\n cascade: 'c',\n setNull: 'n',\n};\n// The column kind (and the field type to declare) a reference to each id strategy needs.\nconst ID_COLUMN = {\n uuid: { kind: 'uuid', type: 'uuid' },\n serial: { kind: 'integer', type: 'integer' },\n bigserial: { kind: 'bigint', type: 'bigint' },\n} as const;\n\n/** The model owning a table, for messages. */\nconst modelOfTable = (table: string) =>\n registeredModels().find((m) => {\n try {\n return m.pgTarget?.().table === table;\n } catch {\n return false;\n }\n })?.name ?? table;\n\n// ── Columns ──────────────────────────────────────────────────────────────────\n\nexport type ScalarKind =\n | 'text'\n | 'varchar'\n | 'double'\n | 'integer'\n | 'bigint'\n | 'numeric'\n | 'boolean'\n | 'timestamptz'\n | 'uuid'\n | 'enum';\nexport type ColumnKind = ScalarKind | 'jsonb' | 'array';\n\nexport interface ColumnSpec {\n /** Record key. */\n field: string;\n /** Database column name. */\n column: string;\n kind: ColumnKind;\n /** Type in DDL (`varchar(80)`, `integer[]`, `\"orders_status_enum\"`). */\n ddl: string;\n /** The same type as `format_type()` prints it, to compare with the live table. */\n formatted: string;\n /** Element kind of a native array column. */\n item?: ScalarKind;\n /** Schema node (absent for id and timestamps). */\n node?: FieldNode;\n /** `bigint` columns: JS `bigint` values, or `number` (sequences, defineModel). */\n bigintAs?: 'bigint' | 'number';\n length?: number;\n precision?: number;\n scale?: number;\n enumType?: string;\n enumValues?: string[];\n}\n\n/** A many-to-many `ref` array on defineTable, stored in a join table instead of a column. */\nexport interface JoinSpec {\n field: string;\n /** The join table: `<table>_<column>`, holding (owner_id, ref_id, position). */\n table: string;\n /** Where the array lived before it had a join table (backfilled from on first sync). */\n legacyColumn: string;\n target: string;\n /** Element kind: the target's id type. */\n item: 'uuid' | 'integer' | 'bigint';\n /** Array type of the ids (`uuid[]`, `integer[]`, `bigint[]`). */\n ddl: string;\n node: FieldNode;\n}\n\ntype ScalarSpec = Pick<\n ColumnSpec,\n 'kind' | 'ddl' | 'formatted' | 'length' | 'precision' | 'scale' | 'bigintAs'\n>;\n\nfunction scalarSpec(type: ScalarType, def: AnyFieldDefinition, native: boolean): ScalarSpec {\n switch (type) {\n case 'string':\n if (native && def.maxLength !== undefined) {\n return {\n kind: 'varchar',\n ddl: `varchar(${def.maxLength})`,\n formatted: `character varying(${def.maxLength})`,\n length: def.maxLength,\n };\n }\n return { kind: 'text', ddl: 'text', formatted: 'text' };\n case 'number':\n return { kind: 'double', ddl: 'double precision', formatted: 'double precision' };\n case 'integer':\n return { kind: 'integer', ddl: 'integer', formatted: 'integer' };\n case 'bigint':\n return { kind: 'bigint', ddl: 'bigint', formatted: 'bigint', bigintAs: 'bigint' };\n case 'decimal': {\n if (def.precision === undefined)\n return { kind: 'numeric', ddl: 'numeric', formatted: 'numeric' };\n const t = `numeric(${def.precision},${def.scale ?? 0})`;\n return {\n kind: 'numeric',\n ddl: t,\n formatted: t,\n precision: def.precision,\n scale: def.scale ?? 0,\n };\n }\n case 'boolean':\n return { kind: 'boolean', ddl: 'boolean', formatted: 'boolean' };\n case 'date':\n return { kind: 'timestamptz', ddl: 'timestamptz', formatted: 'timestamp with time zone' };\n case 'objectId':\n case 'uuid':\n return { kind: 'uuid', ddl: 'uuid', formatted: 'uuid' };\n case 'decimal128':\n case 'long':\n case 'geoPoint':\n case 'binary':\n // The schema builder refuses MongoDB-only types outside defineCollection.\n throw new Error(`[EFC] type '${type}' is MongoDB-only`);\n }\n}\n\nexport interface PgTableConfig {\n /** defineTable: SQL-native types, native arrays, varchar, enums, naming, id strategies. */\n native: boolean;\n /** Which API defined it, for messages. */\n api: 'defineModel' | 'defineTable';\n}\n\nexport type IdKind = 'uuid' | 'serial' | 'bigserial';\n\nexport type PgTable = ReturnType<typeof pgTable>;\n\nexport function pgTable(\n name: string,\n tree: SchemaTree,\n options: ModelOptions & TableOptions,\n config: PgTableConfig,\n) {\n const snake = config.native && options.naming === 'snake_case';\n const table = options.collection ?? tableNameFor(snake ? snakeCase(name) : name);\n const columnName = (field: string, def?: AnyFieldDefinition) =>\n def?.column ?? (snake ? snakeCase(field) : field);\n const idKind: IdKind = (config.native && options.id) || 'uuid';\n if (tree['id']) throw new Error(`[EFC] ${name}: \"id\" is the primary key — don't declare it`);\n\n const ts = timestampFields(options);\n const sequences = sequenceFields(name, tree);\n const sequenceKeys = new Map(sequences.map((s) => [s.path, s.key]));\n const refs = refFields(tree);\n\n const columns = new Map<string, ColumnSpec>();\n const joins = new Map<string, JoinSpec>();\n const idSpec: ColumnSpec =\n idKind === 'uuid'\n ? { field: 'id', column: 'id', kind: 'uuid', ddl: 'uuid', formatted: 'uuid' }\n : idKind === 'serial'\n ? { field: 'id', column: 'id', kind: 'integer', ddl: 'integer', formatted: 'integer' }\n : {\n field: 'id',\n column: 'id',\n kind: 'bigint',\n ddl: 'bigint',\n formatted: 'bigint',\n bigintAs: 'bigint',\n };\n columns.set('id', idSpec);\n\n for (const [field, node] of Object.entries(tree)) {\n const column = columnName(field, node.def);\n const base = { field, column, node };\n if (sequenceKeys.has(field)) {\n columns.set(field, {\n ...base,\n kind: 'bigint',\n ddl: 'bigint',\n formatted: 'bigint',\n bigintAs: 'number',\n });\n } else if (node.kind === 'scalar') {\n if (config.native && node.def.nativeEnum && node.def.enum) {\n const enumType = `${table}_${column}_enum`;\n columns.set(field, {\n ...base,\n kind: 'enum',\n ddl: q(enumType),\n formatted: /^[a-z_][a-z0-9_]*$/.test(enumType) ? enumType : q(enumType),\n enumType,\n enumValues: node.def.enum.map(String),\n });\n } else {\n columns.set(field, { ...base, ...scalarSpec(node.type, node.def, config.native) });\n }\n } else if (\n config.native &&\n node.kind === 'array' &&\n node.item.kind === 'scalar' &&\n node.def.ref !== undefined\n ) {\n // Many-to-many: a join table, not a column.\n const item = scalarSpec(node.item.type, node.item.def, false).kind as JoinSpec['item'];\n joins.set(field, {\n field,\n table: `${table}_${column}`,\n legacyColumn: column,\n target: node.def.ref,\n item,\n ddl: `${item}[]`,\n node,\n });\n } else if (config.native && node.kind === 'array' && node.item.kind === 'scalar') {\n // Items are plain scalars: no varchar length, no enum type.\n const item = scalarSpec(node.item.type, node.item.def, false);\n columns.set(field, {\n ...base,\n ...item,\n kind: 'array',\n item: item.kind as ScalarKind,\n ddl: `${item.ddl}[]`,\n formatted: `${item.formatted}[]`,\n });\n } else {\n columns.set(field, { ...base, kind: 'jsonb', ddl: 'jsonb', formatted: 'jsonb' });\n }\n }\n for (const field of [ts.createdAt, ts.updatedAt]) {\n if (field) {\n columns.set(field, {\n field,\n column: columnName(field),\n kind: 'timestamptz',\n ddl: 'timestamptz',\n formatted: 'timestamp with time zone',\n });\n }\n }\n const byColumn = new Map([...columns.values()].map((c) => [c.column, c]));\n\n // ── Drizzle table ──────────────────────────────────────────────────────────\n\n const builder = (pgCore: any, kind: ScalarKind, spec: ColumnSpec) => {\n const c = spec.column;\n switch (kind) {\n case 'varchar':\n return pgCore.varchar(c, { length: spec.length });\n case 'double':\n return pgCore.doublePrecision(c);\n case 'integer':\n return pgCore.integer(c);\n case 'bigint':\n return pgCore.bigint(c, { mode: spec.bigintAs ?? 'bigint' });\n case 'numeric':\n return pgCore.numeric(\n c,\n spec.precision !== undefined ? { precision: spec.precision, scale: spec.scale } : {},\n );\n case 'boolean':\n return pgCore.boolean(c);\n case 'timestamptz':\n return pgCore.timestamp(c, { withTimezone: true, mode: 'date' });\n case 'uuid':\n return pgCore.uuid(c);\n default:\n return pgCore.text(c); // text, enum (PostgreSQL casts parameters to the enum type)\n }\n };\n\n let compiled: Promise<{ t: any; sql: any }> | undefined;\n const compile = () =>\n (compiled ??= loadDrizzle().then(({ sql, pgCore }) => {\n const cols: AnyRecord = {};\n for (const [field, spec] of columns) {\n let c: any;\n if (spec.kind === 'jsonb') c = pgCore.jsonb(spec.column);\n else if (spec.kind === 'array') c = builder(pgCore, spec.item!, spec).array();\n else c = builder(pgCore, spec.kind, spec);\n if (field === 'id') {\n c =\n idKind === 'uuid'\n ? c.primaryKey().defaultRandom()\n : c.primaryKey().generatedByDefaultAsIdentity();\n }\n cols[field] = c;\n }\n return { t: pgCore.pgTable(table, cols), sql };\n }));\n\n // Like MongoDB creating collections and indexes on first use: the first query through\n // this model reconciles its table (unless autoSync is off). Memoised per process; a\n // failure is retried on the next use instead of being cached.\n let synced: Promise<void> | undefined;\n const ready = async () => {\n const result = await compile();\n if (isAutoSync()) {\n synced ??= reconcile(false).then(\n (changes) => {\n if (changes.length)\n getLogger().info({ table, changes: changes.length }, `Synced table ${table}`);\n },\n (err: unknown) => {\n synced = undefined;\n throw err;\n },\n );\n await synced;\n }\n return result;\n };\n\n const client = () => {\n const tx = currentTx();\n return tx?.engine === 'postgresql' ? tx.tx : getOrm();\n };\n\n const columnFor = (t: any, field: string) => {\n if (!columns.has(field))\n throw new ModelValidationError(name, [{ path: field, message: 'unknown field' }]);\n return t[field];\n };\n\n // ── Values in and out ──────────────────────────────────────────────────────\n\n const scalarToDb = (kind: ScalarKind | undefined, spec: ColumnSpec, v: unknown): unknown => {\n if (v == null) return v;\n if (kind === 'timestamptz') return v instanceof Date ? v : new Date(v as string);\n if (kind === 'bigint')\n return spec.bigintAs === 'number' ? Number(v) : BigInt(v as bigint | number | string);\n if (kind === 'numeric') return String(v);\n return v;\n };\n\n /** A record value → what the Drizzle column takes. */\n const toDb = (field: string, value: unknown): unknown => {\n const spec = columns.get(field);\n if (!spec || value == null) return value;\n if (spec.kind === 'array') {\n return Array.isArray(value) ? value.map((v) => scalarToDb(spec.item, spec, v)) : value;\n }\n if (spec.kind === 'jsonb') return value;\n return scalarToDb(spec.kind, spec, value);\n };\n\n // jsonb keeps dates as ISO strings; turn the ones the schema declares back into Dates,\n // as MongoDB returns them.\n const revive = (node: FieldNode, value: unknown): unknown => {\n if (value == null) return value;\n if (node.kind === 'scalar') {\n if (node.type === 'date' && typeof value === 'string') return new Date(value);\n return value;\n }\n if (node.kind === 'array' && Array.isArray(value))\n return value.map((v) => revive(node.item, v));\n if (node.kind === 'object' && typeof value === 'object' && !Array.isArray(value)) {\n const out: AnyRecord = { ...(value as AnyRecord) };\n for (const [k, child] of Object.entries(node.fields)) {\n if (out[k] !== undefined) out[k] = revive(child, out[k]);\n }\n return out;\n }\n return value;\n };\n const hasNestedDate = (node: FieldNode): boolean =>\n node.kind === 'scalar'\n ? node.type === 'date'\n : node.kind === 'array'\n ? hasNestedDate(node.item)\n : node.kind === 'object' && Object.values(node.fields).some(hasNestedDate);\n const datedJson = [...columns.values()].filter(\n (c) => c.kind === 'jsonb' && c.node && hasNestedDate(c.node),\n );\n const bigintCols = [...columns.values()].filter(\n (c) =>\n (c.kind === 'bigint' && c.bigintAs === 'bigint') ||\n (c.kind === 'array' && c.item === 'bigint'),\n );\n\n /** A Drizzle row (keyed by field) → a record: NULLs dropped, so unset fields are absent. */\n const fromRow = (row: AnyRecord): AnyRecord => {\n const out: AnyRecord = {};\n for (const [k, v] of Object.entries(row)) if (v !== null) out[k] = v;\n for (const c of datedJson)\n if (out[c.field] !== undefined) out[c.field] = revive(c.node!, out[c.field]);\n for (const c of bigintCols) {\n const v = out[c.field];\n if (typeof v === 'string' || typeof v === 'number') out[c.field] = BigInt(v);\n else if (Array.isArray(v)) out[c.field] = v.map((x) => (x == null ? x : BigInt(x as string)));\n }\n return out;\n };\n\n /** A raw SQL row (keyed by column) → a record. */\n const fromRawRow = (row: AnyRecord): AnyRecord => {\n const keyed: AnyRecord = {};\n for (const [col, v] of Object.entries(row)) {\n const spec = byColumn.get(col);\n if (!spec) continue;\n keyed[spec.field] =\n v != null && spec.kind === 'timestamptz' && !(v instanceof Date)\n ? new Date(v as string)\n : v;\n }\n return fromRow(keyed);\n };\n\n const validate = async (data: AnyRecord, partial: boolean) => {\n const issues: FieldIssue[] = [];\n const checkTree: SchemaTree = {};\n for (const [k, node] of Object.entries(tree)) {\n // The database assigns sequence values, so they can't be \"missing\" on insert.\n checkTree[k] = sequenceKeys.has(k)\n ? ({ ...node, def: { ...node.def, required: false } } as FieldNode)\n : node;\n }\n await validateTree(checkTree, data, issues, partial);\n if (issues.length) throw new ModelValidationError(name, issues);\n };\n\n // Undeclared fields are dropped silently on every write (mongoose's strict mode).\n const known = (data: AnyRecord): AnyRecord =>\n Object.fromEntries(\n Object.entries(data).filter(([k]) => {\n const top = k.split('.')[0]!;\n return columns.has(top) || joins.has(top);\n }),\n );\n\n const prepareInsert = async (input: AnyRecord): Promise<AnyRecord> => {\n const { id, ...rest } = known(input);\n for (const f of [ts.createdAt, ts.updatedAt]) if (f) delete rest[f];\n const data = applyDefaults(tree, rest, randomUUID);\n await validate(data, false);\n const now = new Date();\n if (ts.createdAt) data[ts.createdAt] = now;\n if (ts.updatedAt) data[ts.updatedAt] = now;\n if (id !== undefined) data['id'] = id;\n for (const [k, v] of Object.entries(data)) data[k] = toDb(k, v);\n return data;\n };\n\n const fieldOfColumn = (column: string) => byColumn.get(column)?.field ?? column;\n\n /** Maps PostgreSQL errors to EFC's: 409 duplicates, 400 validation, a hint for missing tables. */\n const guard = async <R>(fn: () => Promise<R>): Promise<R> => {\n try {\n return await fn();\n } catch (err) {\n const e =\n (err as { cause?: { code?: string; detail?: string; column?: string; table?: string } })\n .cause ?? (err as { code?: string; detail?: string; column?: string; table?: string });\n if (e?.code === '42P01') {\n throw new Error(\n `[EFC] ${name}: table \"${table}\" does not exist — autoSync is off, so create it with a migration (Model.sync() / efc db sync)`,\n );\n }\n if (e?.code === '23505') {\n const cols = /\\(([^)]+)\\)=/.exec(e.detail ?? '')?.[1] ?? 'field';\n const fields = cols\n .split(',')\n .map((c) => fieldOfColumn(c.trim().replace(/\"/g, '')))\n .join(', ');\n throw new HttpError(409, `${name} with this ${fields} already exists`);\n }\n // 23503 foreign_key_violation; 23001 restrict_violation (ON DELETE RESTRICT).\n if (e?.code === '23503' || e?.code === '23001') {\n const ref = /Key \\(([^)]+)\\)=\\([^)]*\\) is not present in table \"([^\"]+)\"/.exec(\n e.detail ?? '',\n );\n if (ref) {\n throw new ModelValidationError(name, [\n {\n // In a join table: the many-to-many field it backs.\n path: joinByTable.get(e.table ?? '') ?? fieldOfColumn(ref[1]!.replace(/\"/g, '')),\n message: `${modelOfTable(ref[2]!)} not found`,\n },\n ]);\n }\n const by = /is (?:still )?referenced from table \"([^\"]+)\"/.exec(e.detail ?? '')?.[1];\n throw new HttpError(\n 409,\n `${name} is still referenced${by ? ` by ${modelOfTable(by)}` : ''} — delete or reassign those records first`,\n );\n }\n if (e?.code === '23502')\n throw new ModelValidationError(name, [\n { path: fieldOfColumn(e.column ?? ''), message: 'is required' },\n ]);\n if (e?.code === '22P02' || e?.code === '22003' || e?.code === '23514')\n throw new ModelValidationError(name, [{ path: '', message: 'invalid value' }]);\n throw err;\n }\n };\n\n // ── Schema reconciliation ──────────────────────────────────────────────────\n // Brings the table in line with the model the way MongoDB \"just works\" when a schema\n // changes: create what's missing, convert changed column types, relax constraints the\n // model no longer asks for, rebuild enum checks, drop indexes EFC created that the\n // model no longer declares. Never drops a column or a row. Validation (required,\n // enum, ...) stays in the model, as on MongoDB — the database only keeps types,\n // uniqueness and enum checks, so editing a model can't strand existing rows.\n\n const JSONB_TO_ARRAY = 'efc_jsonb_text_array';\n const jsonbToArrayFn = `CREATE OR REPLACE FUNCTION ${JSONB_TO_ARRAY}(j jsonb) RETURNS text[] LANGUAGE sql IMMUTABLE AS $$ SELECT CASE WHEN j IS NULL OR jsonb_typeof(j) = 'null' THEN NULL WHEN jsonb_typeof(j) = 'array' THEN ARRAY(SELECT jsonb_array_elements_text(j)) ELSE ARRAY[j #>> '{}'] END $$`;\n\n // USING expression converting an existing column to the model's type.\n const castExpr = (spec: ColumnSpec, from: string): string => {\n const c = q(spec.column);\n if (spec.kind === 'jsonb') return `to_jsonb(${c})`;\n if (spec.kind === 'array') {\n if (from === 'jsonb') return `${JSONB_TO_ARRAY}(${c})::${spec.ddl}`;\n if (from.endsWith('[]')) return `${c}::${spec.ddl}`;\n return `CASE WHEN ${c} IS NULL THEN NULL ELSE ARRAY[${c}::text]::${spec.ddl} END`;\n }\n const scalar = from === 'jsonb' ? `(${c} #>> '{}')` : c;\n if (spec.kind === 'enum') return `${scalar}::text::${spec.ddl}`;\n if (spec.kind === 'bigint' || spec.kind === 'integer') {\n return `round(${scalar}::numeric)::${spec.ddl}`;\n }\n return `${scalar}::${spec.ddl}`;\n };\n\n // varchar never shrinks (and a text column isn't narrowed to varchar): rows could stop fitting.\n const needsTypeChange = (spec: ColumnSpec, existing: string): boolean => {\n if (existing === spec.formatted) return false;\n if (spec.kind === 'varchar') {\n if (existing === 'text') return false;\n const m = /^character varying\\((\\d+)\\)$/.exec(existing);\n if (m && Number(m[1]) >= spec.length!) return false;\n }\n return true;\n };\n\n const enumCheck = (column: string) => `${table}_${column}_enum`;\n\n // ── Foreign keys (defineTable refs) ────────────────────────────────────────\n\n interface ForeignKey {\n field: string;\n /** The table holding the constraint: this one, or one of its join tables. */\n onTable: string;\n column: string;\n name: string;\n target: string;\n targetTable: string;\n action: ReferentialAction;\n }\n\n const fkName = (column: string) => `${table}_${column}_fkey`;\n const isForeignKey = (spec: ColumnSpec) =>\n config.native && spec.node?.kind === 'scalar' && spec.node.def.ref !== undefined;\n\n /** A `ref`'s target table, checked against the field's id type. */\n function resolveTarget(field: string, targetName: string, kind: string, many: boolean) {\n const target =\n targetName === name ? { table, idKind } : getRegisteredModel(targetName)?.pgTarget?.();\n if (!target) {\n throw new Error(\n `[EFC] ${name}.${field} references \"${targetName}\", which is not defined — import that model before using ${name}`,\n );\n }\n const want = ID_COLUMN[target.idKind];\n if (kind !== want.kind) {\n const hint = many\n ? `{ type: 'array', of: '${want.type}', ref: '${targetName}' }`\n : `{ type: '${want.type}', ref: '${targetName}' }`;\n throw new Error(\n `[EFC] ${name}.${field} references ${targetName}, whose id is ${want.type} (id: '${target.idKind}') — declare it ${hint}`,\n );\n }\n return target;\n }\n\n /**\n * The foreign keys the model declares, resolved against their target models: one per\n * scalar ref, and two per join table (to this table and to the target, both cascading).\n */\n function foreignKeys(): ForeignKey[] {\n const out: ForeignKey[] = [];\n for (const spec of columns.values()) {\n if (!isForeignKey(spec)) continue;\n const def = spec.node!.def;\n const target = resolveTarget(spec.field, def.ref!, spec.kind, false);\n out.push({\n field: spec.field,\n onTable: table,\n column: spec.column,\n name: fkName(spec.column),\n target: def.ref!,\n targetTable: target.table,\n action: def.onDelete ?? 'restrict',\n });\n }\n for (const join of joins.values()) {\n const target = resolveTarget(join.field, join.target, join.item, true);\n const base = { field: join.field, onTable: join.table, action: 'cascade' as const };\n out.push(\n {\n ...base,\n column: 'owner_id',\n name: `${join.table}_owner_id_fkey`,\n target: name,\n targetTable: table,\n },\n {\n ...base,\n column: 'ref_id',\n name: `${join.table}_ref_id_fkey`,\n target: join.target,\n targetTable: target.table,\n },\n );\n }\n return out;\n }\n\n const joinByTable = new Map([...joins.values()].map((j) => [j.table, j.field]));\n const managedIndexName = /_(key|idx)$/;\n\n function desiredIndexes(): Map<string, string> {\n const out = new Map<string, string>();\n for (const spec of columns.values()) {\n const def = spec.node?.def;\n if (!def) continue;\n const col = spec.column;\n if (def.unique) {\n out.set(\n `${table}_${col}_key`,\n `CREATE UNIQUE INDEX ${q(`${table}_${col}_key`)} ON ${q(table)} (${q(col)})`,\n );\n } else if (def.index || (isForeignKey(spec) && def.index !== false)) {\n // Foreign key columns are indexed (joins, ON DELETE lookups) unless index: false.\n out.set(\n `${table}_${col}_idx`,\n `CREATE INDEX ${q(`${table}_${col}_idx`)} ON ${q(table)} (${q(col)})`,\n );\n }\n }\n for (const idx of options.indexes ?? []) {\n const fields = Object.entries(idx.fields).map(\n ([f, d]) => [columns.get(f)?.column ?? f, d] as const,\n );\n if (idx.expireAfterSeconds !== undefined) {\n throw new Error(`[EFC] ${name}: TTL indexes (expireAfterSeconds) are MongoDB-only`);\n }\n const idxName =\n idx.name ?? `${table}_${fields.map(([f]) => f).join('_')}_${idx.unique ? 'key' : 'idx'}`;\n if (fields.some(([, d]) => d === 'text')) {\n const doc = fields.map(([f]) => `coalesce(${q(f)}::text, '')`).join(` || ' ' || `);\n out.set(\n idxName,\n `CREATE INDEX ${q(idxName)} ON ${q(table)} USING gin (to_tsvector('simple', ${doc}))`,\n );\n } else {\n const cols = fields.map(([f, d]) => `${q(f)} ${d === -1 ? 'DESC' : 'ASC'}`).join(', ');\n out.set(\n idxName,\n `CREATE ${idx.unique ? 'UNIQUE ' : ''}INDEX ${q(idxName)} ON ${q(table)} (${cols})`,\n );\n }\n }\n return out;\n }\n\n const tableExists = async (t: string) =>\n (\n await getPool().query(\n `SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relname = $1 AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,\n [t],\n )\n ).rowCount! > 0;\n\n /**\n * Syncs the table. A foreign key needs its target table, so missing targets are synced\n * first; one whose sync is already running here (A ↔ B references) is skipped this pass\n * and added by a second pass once that sync finishes.\n */\n async function reconcile(dryRun: boolean): Promise<string[]> {\n if (isSyncSuppressed()) return [];\n const fks = foreignKeys();\n if (dryRun) return statements(await reconcileTable({ dryRun: true }, fks, new Set()));\n let release!: () => void;\n const mine = new Promise<void>((resolve) => (release = resolve));\n const prev = syncing.get(table);\n syncing.set(table, mine);\n try {\n const deferred = new Set<string>();\n // First used inside a transaction: adding a foreign key locks the referenced table,\n // which that transaction may already have written to — the sync (on its own\n // connection) and the transaction would wait for each other forever. Create the\n // tables now; add the keys once the transaction has committed.\n const tx = currentTx();\n if (tx?.engine === 'postgresql' && fks.length) {\n for (const fk of fks) deferred.add(fk.name);\n tx.afterCommit.push(() => {\n reconcile(false).catch((err: unknown) =>\n getLogger().error({ err }, `${name}: adding foreign keys to \"${table}\" failed`),\n );\n });\n }\n for (const fk of fks) {\n if (deferred.has(fk.name)) continue;\n if (fk.targetTable === table || (await tableExists(fk.targetTable))) continue;\n const running = syncing.get(fk.targetTable);\n if (running) {\n deferred.add(fk.name);\n void running\n .then(() => reconcile(false))\n .catch((err: unknown) =>\n getLogger().error({ err }, `${name}: adding foreign keys to \"${table}\" failed`),\n );\n } else {\n await getRegisteredModel(fk.target)!.sync();\n }\n }\n return statements(await reconcileTable({ dryRun: false }, fks, deferred));\n } finally {\n release();\n if (syncing.get(table) === mine) {\n if (prev) syncing.set(table, prev);\n else syncing.delete(table);\n }\n }\n }\n\n const statements = (steps: PlanStep[]) => steps.filter((s) => !s.check).map((s) => s.sql);\n\n /**\n * The migration `efc db generate` writes for this table: what sync would do, plus the\n * explicit extras (`allowDrop`, `tighten`), each step with a best-effort reverse.\n */\n function plan(options: PlanOptions = {}): Promise<PlanStep[]> {\n return reconcileTable({ dryRun: true, plan: options }, foreignKeys(), new Set());\n }\n\n async function reconcileTable(\n mode: { dryRun: boolean; plan?: PlanOptions },\n fks: ForeignKey[],\n deferred: Set<string>,\n ): Promise<PlanStep[]> {\n const { dryRun } = mode;\n const generating = mode.plan !== undefined;\n const pool = getPool();\n const conn = await pool.connect();\n try {\n await conn.query('BEGIN');\n // Serialises concurrent syncs of this table (every cluster worker runs one on boot).\n await conn.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`efc_sync:${table}`]);\n\n const existing = new Map<string, { type: string; nullable: boolean }>(\n (\n await conn.query<{ name: string; type: string; nullable: boolean }>(\n `SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, NOT a.attnotnull AS nullable\n FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relname = $1 AND n.nspname = current_schema() AND a.attnum > 0 AND NOT a.attisdropped`,\n [table],\n )\n ).rows.map((r) => [r.name, { type: r.type, nullable: r.nullable }]),\n );\n const checks = new Map<string, { def: string; valid: boolean }>(\n (\n await conn.query<{ name: string; def: string; valid: boolean }>(\n `SELECT con.conname AS name, pg_get_constraintdef(con.oid) AS def, con.convalidated AS valid\n FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relname = $1 AND n.nspname = current_schema() AND con.contype = 'c'`,\n [table],\n )\n ).rows.map((r) => [r.name, { def: r.def, valid: r.valid }]),\n );\n const indexes = new Map(\n (\n await conn.query<{ name: string; def: string }>(\n `SELECT indexname AS name, indexdef AS def FROM pg_indexes WHERE tablename = $1 AND schemaname = current_schema()`,\n [table],\n )\n ).rows.map((r) => [r.name, r.def]),\n );\n\n const liveFks = new Map(\n (\n await conn.query<{\n name: string;\n target: string;\n action: string;\n valid: boolean;\n def: string;\n }>(\n `SELECT con.conname AS name, ft.relname AS target, con.confdeltype AS action, con.convalidated AS valid,\n pg_get_constraintdef(con.oid) AS def\n FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN pg_class ft ON ft.oid = con.confrelid\n WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND con.contype = 'f'`,\n [[table, ...joinByTable.keys()]],\n )\n ).rows.map((r) => [r.name, r]),\n );\n const liveJoinTables = new Set(\n (\n await conn.query<{ name: string }>(\n `SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,\n [[...joinByTable.keys()]],\n )\n ).rows.map((r) => r.name),\n );\n\n const steps: PlanStep[] = [];\n const add = (sql: string, extra: Omit<Partial<PlanStep>, 'sql'> = {}) => {\n if (!steps.some((s) => s.sql === sql)) steps.push({ phase: 'main', ...extra, sql });\n };\n const columnExists = (column: string) =>\n `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ${literal(table)} AND column_name = ${literal(column)}`;\n\n // Foreign keys on the model's fields that it no longer declares (or declares\n // differently) go first, before any column type change. Constraints on columns the\n // model doesn't declare are left alone.\n const wantedFks = new Map(fks.map((fk) => [fk.name, fk]));\n for (const [con, live] of liveFks) {\n const want = wantedFks.get(con);\n // Join tables are entirely EFC's.\n const ours =\n [...joinByTable.keys()].some((jt) => con.startsWith(`${jt}_`)) ||\n [...columns.values()].some((c) => c.field !== 'id' && fkName(c.column) === con);\n if (\n ours &&\n (!want || live.target !== want.targetTable || live.action !== ACTION_CODE[want.action])\n ) {\n const on = [...joinByTable.keys()].find((jt) => con.startsWith(`${jt}_`)) ?? table;\n add(`ALTER TABLE ${q(on)} DROP CONSTRAINT IF EXISTS ${q(con)}`, {\n down: `ALTER TABLE ${q(on)} ADD CONSTRAINT ${q(con)} ${live.def}`,\n });\n liveFks.delete(con);\n }\n }\n for (const { key } of sequences) {\n const seq = sequenceName(key);\n const found = await conn.query(\n `SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind = 'S' AND c.relname = $1 AND n.nspname = current_schema()`,\n [seq],\n );\n if (found.rowCount === 0)\n add(`CREATE SEQUENCE IF NOT EXISTS ${q(seq)}`, {\n down: `DROP SEQUENCE IF EXISTS ${q(seq)}`,\n });\n }\n\n // Native enum types: create, or add values the model gained. Values are never\n // removed (rows may hold them); the model rejects them on writes.\n const enumSpecs = [...columns.values()].filter((c) => c.kind === 'enum');\n if (enumSpecs.length) {\n const live = new Map<string, Set<string>>();\n for (const r of (\n await conn.query<{ type: string; label: string | null }>(\n `SELECT t.typname AS type, e.enumlabel AS label FROM pg_type t\n JOIN pg_namespace n ON n.oid = t.typnamespace LEFT JOIN pg_enum e ON e.enumtypid = t.oid\n WHERE n.nspname = current_schema() AND t.typname = ANY($1)`,\n [enumSpecs.map((c) => c.enumType)],\n )\n ).rows) {\n const set = live.get(r.type) ?? new Set<string>();\n if (r.label !== null) set.add(r.label);\n live.set(r.type, set);\n }\n for (const spec of enumSpecs) {\n const have = live.get(spec.enumType!);\n if (!have) {\n add(`CREATE TYPE ${spec.ddl} AS ENUM (${spec.enumValues!.map(literal).join(', ')})`, {\n down: `DROP TYPE IF EXISTS ${spec.ddl}`,\n skipIf: `SELECT 1 FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = current_schema() AND t.typname = ${literal(spec.enumType!)}`,\n });\n } else {\n for (const v of spec.enumValues!) {\n if (!have.has(v)) add(`ALTER TYPE ${spec.ddl} ADD VALUE IF NOT EXISTS ${literal(v)}`);\n }\n }\n }\n }\n\n const columnSql = (spec: ColumnSpec) => {\n const seq = sequenceKeys.get(spec.field);\n return `${q(spec.column)} ${spec.ddl}${seq ? ` DEFAULT nextval('${sequenceName(seq)}')` : ''}`;\n };\n const idSql =\n idKind === 'uuid'\n ? `${q('id')} uuid PRIMARY KEY DEFAULT gen_random_uuid()`\n : `${q('id')} ${idSpec.ddl} GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`;\n const isRequired = (spec: ColumnSpec) =>\n spec.field !== 'id' && spec.node?.kind !== undefined && spec.node.def.required === true;\n\n if (existing.size === 0) {\n const defs = [...columns.values()].map((spec) =>\n spec.field === 'id' ? idSql : columnSql(spec),\n );\n add(`CREATE TABLE IF NOT EXISTS ${q(table)} (\\n ${defs.join(',\\n ')}\\n)`, {\n down: `DROP TABLE IF EXISTS ${q(table)}`,\n });\n } else {\n // Renames first: `renamedFrom` moves the old column (and its data) to the new name\n // instead of adding an empty one beside it.\n for (const spec of columns.values()) {\n const old = spec.node?.def.renamedFrom;\n if (old === undefined || existing.has(spec.column)) continue;\n const oldColumn = columnName(old);\n const col = existing.get(oldColumn);\n if (!col) continue;\n add(`ALTER TABLE ${q(table)} RENAME COLUMN ${q(oldColumn)} TO ${q(spec.column)}`, {\n down: `ALTER TABLE ${q(table)} RENAME COLUMN ${q(spec.column)} TO ${q(oldColumn)}`,\n skipIf: columnExists(spec.column),\n });\n existing.delete(oldColumn);\n existing.set(spec.column, col);\n }\n for (const spec of columns.values()) {\n const col = existing.get(spec.column);\n if (!col) {\n add(`ALTER TABLE ${q(table)} ADD COLUMN IF NOT EXISTS ${columnSql(spec)}`, {\n down: `ALTER TABLE ${q(table)} DROP COLUMN IF EXISTS ${q(spec.column)}`,\n });\n } else if (spec.field !== 'id' && needsTypeChange(spec, col.type)) {\n if (spec.kind === 'array' && col.type === 'jsonb') add(jsonbToArrayFn, { down: '' });\n const back =\n col.type === 'jsonb'\n ? `to_jsonb(${q(spec.column)})`\n : `${q(spec.column)}::${col.type}`;\n add(\n `ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} TYPE ${spec.ddl} USING ${castExpr(spec, col.type)}`,\n {\n down: `ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} TYPE ${col.type} USING ${back}`,\n skipIf: `SELECT 1 FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = ${literal(table)} AND a.attname = ${literal(spec.column)} AND format_type(a.atttypid, a.atttypmod) = ${literal(spec.formatted)}`,\n },\n );\n }\n }\n // NOT NULL is the model's job (validation), as on MongoDB: relax any the model\n // doesn't ask for — left over from an older model, an earlier EFC version, or a\n // column it no longer declares — so dropping/loosening a field never breaks inserts.\n for (const [column, col] of existing) {\n const spec = byColumn.get(column);\n if (column !== 'id' && !col.nullable && !(spec && isRequired(spec))) {\n add(`ALTER TABLE ${q(table)} ALTER COLUMN ${q(column)} DROP NOT NULL`, {\n down: `ALTER TABLE ${q(table)} ALTER COLUMN ${q(column)} SET NOT NULL`,\n });\n }\n }\n }\n\n // Enum checks: one managed constraint per (non-native) enum field, rebuilt when the\n // values change. NOT VALID: like MongoDB, existing rows aren't re-validated.\n const wantedChecks = new Map<string, string>();\n for (const spec of columns.values()) {\n const def = spec.node?.def;\n if (spec.node?.kind === 'scalar' && def?.enum && spec.kind !== 'enum') {\n wantedChecks.set(\n enumCheck(spec.column),\n `CHECK (${q(spec.column)} IN (${def.enum.map(literal).join(', ')}))`,\n );\n }\n }\n for (const [con, { def }] of checks) {\n const legacy = con.endsWith('_check') && con.startsWith(`${table}_`); // inline CHECKs from older EFC\n const drop = () => {\n add(`ALTER TABLE ${q(table)} DROP CONSTRAINT IF EXISTS ${q(con)}`, {\n down: `ALTER TABLE ${q(table)} ADD CONSTRAINT ${q(con)} ${def}`,\n });\n checks.delete(con);\n };\n if (\n (con.endsWith('_enum') && con.startsWith(`${table}_`) && !wantedChecks.has(con)) ||\n legacy\n ) {\n drop();\n } else if (wantedChecks.has(con)) {\n const want = wantedChecks.get(con)!;\n // pg_get_constraintdef normalises the text; compare the value lists only.\n const values = (d: string) =>\n [...d.matchAll(/'((?:[^']|'')*)'|(-?\\d+(?:\\.\\d+)?)/g)]\n .map((m) => m[1] ?? m[2])\n .sort()\n .join('|');\n if (values(def) !== values(want)) drop();\n }\n }\n for (const [con, def] of wantedChecks) {\n if (!checks.has(con))\n add(`ALTER TABLE ${q(table)} ADD CONSTRAINT ${q(con)} ${def} NOT VALID`, {\n down: `ALTER TABLE ${q(table)} DROP CONSTRAINT IF EXISTS ${q(con)}`,\n skipIf: `SELECT 1 FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = ${literal(table)} AND con.conname = ${literal(con)}`,\n });\n }\n\n // Indexes: create declared ones, drop EFC-named ones the model no longer declares.\n const wantedIndexes = desiredIndexes();\n for (const [idx, def] of indexes) {\n if (\n idx !== `${table}_pkey` &&\n idx.startsWith(`${table}_`) &&\n managedIndexName.test(idx) &&\n !wantedIndexes.has(idx)\n ) {\n add(`DROP INDEX IF EXISTS ${q(idx)}`, { down: def });\n }\n }\n for (const [idx, create] of wantedIndexes)\n if (!indexes.has(idx))\n add(create.replace(/^CREATE (UNIQUE )?INDEX /, 'CREATE $1INDEX IF NOT EXISTS '), {\n down: `DROP INDEX IF EXISTS ${q(idx)}`,\n });\n\n // Join tables for many-to-many refs: created once, filled from the array column the\n // field used before (if any). That column is kept, as sync never drops columns.\n const ownerDdl = idSpec.ddl;\n for (const join of joins.values()) {\n if (liveJoinTables.has(join.table)) continue;\n const refDdl = join.item;\n add(\n `CREATE TABLE IF NOT EXISTS ${q(join.table)} (\\n ${q('owner_id')} ${ownerDdl} NOT NULL,\\n ${q('ref_id')} ${refDdl} NOT NULL,\\n ${q('position')} integer NOT NULL DEFAULT 0,\\n PRIMARY KEY (${q('owner_id')}, ${q('ref_id')})\\n)`,\n { down: `DROP TABLE IF EXISTS ${q(join.table)}` },\n );\n add(\n `CREATE INDEX IF NOT EXISTS ${q(`${join.table}_ref_id_idx`)} ON ${q(join.table)} (${q('ref_id')})`,\n { down: '' }, // dropped with the table\n );\n const legacy = existing.get(join.legacyColumn)?.type;\n if (legacy === 'jsonb' || legacy?.endsWith('[]')) {\n const c = `o.${q(join.legacyColumn)}`;\n const items =\n legacy === 'jsonb'\n ? `jsonb_array_elements_text(CASE WHEN jsonb_typeof(${c}) = 'array' THEN ${c} ELSE '[]'::jsonb END)`\n : `unnest(${c}::text[])`;\n const valid =\n join.item === 'uuid'\n ? `'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'`\n : `'^-?[0-9]{1,18}$'`;\n add(\n `INSERT INTO ${q(join.table)} (${q('owner_id')}, ${q('ref_id')}, ${q('position')}) SELECT o.${q('id')}, x.v::${refDdl}, x.n FROM ${q(table)} o, ${items} WITH ORDINALITY AS x(v, n) WHERE x.v ~ ${valid} ON CONFLICT DO NOTHING`,\n { down: '' }, // the old column is kept\n );\n }\n }\n\n // `efc db generate` only, never automatic: changes that can fail on existing rows or\n // lose data. Each tightening is guarded by a check that names the offending rows.\n if (mode.plan?.tighten) {\n for (const spec of columns.values()) {\n if (!isRequired(spec) || existing.get(spec.column)?.nullable === false) continue;\n add(`SELECT count(*)::int AS n FROM ${q(table)} WHERE ${q(spec.column)} IS NULL`, {\n check: `${name}.${spec.field} is required, but %n row(s) of \"${table}\" have no value — fill them in, then run the migration again`,\n });\n add(`ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} SET NOT NULL`, {\n down: `ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} DROP NOT NULL`,\n });\n }\n for (const [con, def] of wantedChecks) {\n if (checks.get(con)?.valid) continue;\n const spec = byColumn.get(con.slice(table.length + 1, -'_enum'.length));\n const values = /IN \\((.*)\\)\\)$/.exec(def)?.[1];\n if (spec && values) {\n add(\n `SELECT count(*)::int AS n FROM ${q(table)} WHERE ${q(spec.column)} IS NOT NULL AND ${q(spec.column)} NOT IN (${values})`,\n {\n check: `${name}.${spec.field}: %n row(s) of \"${table}\" hold a value outside its enum — fix them, then run the migration again`,\n },\n );\n }\n add(`ALTER TABLE ${q(table)} VALIDATE CONSTRAINT ${q(con)}`, { down: '' });\n }\n }\n if (mode.plan?.allowDrop) {\n for (const [column, col] of existing) {\n if (byColumn.has(column)) continue;\n add(`ALTER TABLE ${q(table)} DROP COLUMN IF EXISTS ${q(column)}`, {\n down: `ALTER TABLE ${q(table)} ADD COLUMN IF NOT EXISTS ${q(column)} ${col.type} -- data is not restored`,\n });\n }\n }\n\n // Added NOT VALID — instant, and existing rows can't fail the sync — then validated\n // after the commit, where orphaned rows only produce a warning. A generated\n // migration validates in the same run, behind an orphaned-rows check.\n const toValidate: ForeignKey[] = [];\n for (const fk of fks) {\n if (deferred.has(fk.name)) continue;\n const live = liveFks.get(fk.name);\n if (!live) {\n add(\n `ALTER TABLE ${q(fk.onTable)} ADD CONSTRAINT ${q(fk.name)} FOREIGN KEY (${q(fk.column)}) REFERENCES ${q(fk.targetTable)} (${q('id')}) ON DELETE ${ACTION_SQL[fk.action]} NOT VALID`,\n {\n phase: 'fk',\n down: `ALTER TABLE ${q(fk.onTable)} DROP CONSTRAINT IF EXISTS ${q(fk.name)}`,\n skipIf: `SELECT 1 FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = ${literal(fk.onTable)} AND con.conname = ${literal(fk.name)}`,\n },\n );\n }\n if (!live?.valid) toValidate.push(fk);\n }\n const orphans = (fk: ForeignKey) =>\n `SELECT count(*)::int AS n FROM ${q(fk.onTable)} r WHERE ${q(fk.column)} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${q(fk.targetTable)} t WHERE t.${q('id')} = r.${q(fk.column)})`;\n const validations = toValidate.map(\n (fk) => `ALTER TABLE ${q(fk.onTable)} VALIDATE CONSTRAINT ${q(fk.name)}`,\n );\n if (generating) {\n for (const [i, fk] of toValidate.entries()) {\n add(orphans(fk), {\n phase: 'fk',\n check: `${name}.${fk.field}: %n row(s) reference a missing ${fk.target} — fix them, then run the migration again`,\n });\n add(validations[i]!, { phase: 'fk', down: '' });\n }\n }\n\n if (!dryRun) {\n for (const { sql: stmt } of steps) {\n try {\n await conn.query(stmt);\n } catch (err) {\n throw new Error(\n `[EFC] ${name}: syncing table \"${table}\" failed on: ${stmt}\\n ${(err as Error).message}`,\n );\n }\n }\n }\n await conn.query(dryRun ? 'ROLLBACK' : 'COMMIT');\n if (!dryRun && steps.length) invalidatePreparedStatements(getPool());\n if (!dryRun) {\n for (const [i, fk] of toValidate.entries()) {\n try {\n await conn.query(validations[i]!);\n } catch {\n const n = await conn\n .query<{ n: number }>(orphans(fk))\n .then((r) => r.rows[0]?.n ?? '?')\n .catch(() => '?');\n getLogger().warn(\n { table, constraint: fk.name, orphans: Number(n) },\n `${name}.${fk.field}: ${n} row(s) reference a missing ${fk.target} — the foreign key applies to new writes; fix those rows, then run efc db sync to validate it`,\n );\n }\n }\n }\n return generating\n ? steps\n : [...steps, ...validations.map((sql) => ({ sql, phase: 'fk' as const }))];\n } catch (err) {\n await conn.query('ROLLBACK').catch(() => {});\n throw err;\n } finally {\n conn.release();\n }\n }\n\n async function drop() {\n const { sql } = await compile();\n await client().execute(sql.raw(`DROP TABLE IF EXISTS ${q(table)}`));\n invalidatePreparedStatements(getPool());\n }\n\n return {\n name,\n table,\n tree,\n idKind,\n columns,\n joins,\n ts,\n sequenceKeys,\n refs,\n compile,\n ready,\n client,\n columnFor,\n toDb,\n fromRow,\n fromRawRow,\n validate,\n known,\n prepareInsert,\n guard,\n reconcile,\n plan,\n drop,\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-H2PVWCWC.cjs","../src/tasks/index.ts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A,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-H2PVWCWC.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"]}