express-file-cluster 0.10.0 → 0.10.2

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 (186) hide show
  1. package/dist/auth/index.cjs +7 -6
  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 +5 -5
  6. package/dist/{chunk-R52CUEGT.js → chunk-3SWI46YK.js} +2 -2
  7. package/dist/{chunk-DCJOWFVD.cjs → chunk-4GHK27JA.cjs} +3 -3
  8. package/dist/{chunk-DCJOWFVD.cjs.map → chunk-4GHK27JA.cjs.map} +1 -1
  9. package/dist/{chunk-NI2BNGGV.js → chunk-5LPRKZPB.js} +2 -2
  10. package/dist/chunk-74BSJXWD.cjs +220 -0
  11. package/dist/chunk-74BSJXWD.cjs.map +1 -0
  12. package/dist/{chunk-7KO4DJRJ.cjs → chunk-7BC3AN7R.cjs} +14 -14
  13. package/dist/{chunk-7KO4DJRJ.cjs.map → chunk-7BC3AN7R.cjs.map} +1 -1
  14. package/dist/chunk-AGOYTFRO.cjs +42 -0
  15. package/dist/chunk-AGOYTFRO.cjs.map +1 -0
  16. package/dist/{chunk-RAB44UGX.js → chunk-B6MB6HEG.js} +1 -1
  17. package/dist/{chunk-PGJQK36V.js → chunk-BG4A7Z32.js} +7 -5
  18. package/dist/{chunk-PGJQK36V.js.map → chunk-BG4A7Z32.js.map} +1 -1
  19. package/dist/{chunk-ATVD2HGC.js → chunk-C2FOZ7ME.js} +4 -4
  20. package/dist/chunk-CGY7JU4Y.cjs +8 -0
  21. package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
  22. package/dist/{chunk-EGSSZUVO.js → chunk-DN4TCGYB.js} +38 -11
  23. package/dist/chunk-DN4TCGYB.js.map +1 -0
  24. package/dist/{chunk-GBI77W5T.cjs → chunk-H2PVWCWC.cjs} +1 -1
  25. package/dist/{chunk-GBI77W5T.cjs.map → chunk-H2PVWCWC.cjs.map} +1 -1
  26. package/dist/{chunk-NKLOE4AK.cjs → chunk-IUZ6A7PB.cjs} +20 -53
  27. package/dist/chunk-IUZ6A7PB.cjs.map +1 -0
  28. package/dist/{chunk-DUADUR6R.cjs → chunk-JP36TLL4.cjs} +171 -14
  29. package/dist/chunk-JP36TLL4.cjs.map +1 -0
  30. package/dist/chunk-KLWL7XSC.js +220 -0
  31. package/dist/chunk-KLWL7XSC.js.map +1 -0
  32. package/dist/{chunk-4DOHQU6I.cjs → chunk-M53GODCX.cjs} +39 -12
  33. package/dist/chunk-M53GODCX.cjs.map +1 -0
  34. package/dist/{chunk-R4XO4SVM.js → chunk-MUVO7MGS.js} +4 -4
  35. package/dist/{chunk-HBCY7ILD.cjs → chunk-R2K7AFIB.cjs} +97 -95
  36. package/dist/chunk-R2K7AFIB.cjs.map +1 -0
  37. package/dist/{chunk-QDEDOHP7.js → chunk-RETV3GKE.js} +9 -42
  38. package/dist/chunk-RETV3GKE.js.map +1 -0
  39. package/dist/{chunk-WBLUGOAG.cjs → chunk-RPL2IFWK.cjs} +8 -5
  40. package/dist/chunk-RPL2IFWK.cjs.map +1 -0
  41. package/dist/{chunk-YK4ZM3CA.cjs → chunk-TBIVIR6L.cjs} +15 -15
  42. package/dist/{chunk-YK4ZM3CA.cjs.map → chunk-TBIVIR6L.cjs.map} +1 -1
  43. package/dist/{chunk-73XJUT2S.js → chunk-V73R76I4.js} +162 -5
  44. package/dist/chunk-V73R76I4.js.map +1 -0
  45. package/dist/chunk-XPY5TQDK.js +42 -0
  46. package/dist/chunk-XPY5TQDK.js.map +1 -0
  47. package/dist/{chunk-KFVFP2Q7.cjs → chunk-Y4NKIXUL.cjs} +70 -55
  48. package/dist/chunk-Y4NKIXUL.cjs.map +1 -0
  49. package/dist/{chunk-7KC2H76D.js → chunk-Y75V5FCU.js} +62 -47
  50. package/dist/chunk-Y75V5FCU.js.map +1 -0
  51. package/dist/cli/db-runner.cjs +81 -42
  52. package/dist/cli/db-runner.cjs.map +1 -1
  53. package/dist/cli/db-runner.js +54 -16
  54. package/dist/cli/db-runner.js.map +1 -1
  55. package/dist/cli/index.cjs +23 -25
  56. package/dist/cli/index.cjs.map +1 -1
  57. package/dist/cli/index.js +12 -17
  58. package/dist/cli/index.js.map +1 -1
  59. package/dist/docs/api-reference/auth.md +23 -0
  60. package/dist/docs/api-reference/compose.md +1 -1
  61. package/dist/docs/api-reference/db.md +8 -0
  62. package/dist/docs/api-reference/ignite.md +4 -1
  63. package/dist/docs/api-reference/testing.md +26 -0
  64. package/dist/docs/cli/add.md +2 -2
  65. package/dist/docs/core-concepts/file-based-routing.md +2 -0
  66. package/dist/docs/core-concepts/middleware.md +2 -2
  67. package/dist/docs/getting-started/index.md +4 -0
  68. package/dist/docs/guides/authentication.md +33 -0
  69. package/dist/docs/guides/caching.md +2 -0
  70. package/dist/docs/guides/database.md +15 -0
  71. package/dist/docs/guides/environment-variables.md +6 -0
  72. package/dist/docs/guides/generated-portals.md +3 -1
  73. package/dist/docs/guides/logging.md +17 -0
  74. package/dist/docs/guides/migrations.md +4 -2
  75. package/dist/docs/guides/testing.md +31 -0
  76. package/dist/docs/index.md +2 -1
  77. package/dist/docs/skills/SKILL.md +5 -1
  78. package/dist/docs/skills/api-surface.md +20 -4
  79. package/dist/docs/skills/auth-internals.md +14 -1
  80. package/dist/docs/skills/pre-flight.md +6 -0
  81. package/dist/docs/skills/routing-rules.md +1 -1
  82. package/dist/docs/skills/what-not-to-invent.md +9 -1
  83. package/dist/docs/versioning.md +1 -1
  84. package/dist/index.cjs +75 -264
  85. package/dist/index.cjs.map +1 -1
  86. package/dist/index.d.cts +27 -3
  87. package/dist/index.d.ts +27 -3
  88. package/dist/index.js +28 -218
  89. package/dist/index.js.map +1 -1
  90. package/dist/pgboss-backend-4X2YT4RB.js +14 -0
  91. package/dist/pgboss-backend-UXQ3O2WT.cjs +15 -0
  92. package/dist/pgboss-backend-UXQ3O2WT.cjs.map +1 -0
  93. package/dist/registry/index.json +27 -3
  94. package/dist/registry/js-mongo/account-security.json +1 -1
  95. package/dist/registry/js-mongo/admin-users.json +1 -1
  96. package/dist/registry/js-mongo/auth.json +1 -1
  97. package/dist/registry/js-mongo/auth@apple.json +1 -1
  98. package/dist/registry/js-mongo/auth@google.json +1 -1
  99. package/dist/registry/js-mongo/forgot-password.json +1 -1
  100. package/dist/registry/js-mongo/user-profile.json +1 -1
  101. package/dist/registry/js-mongo-collection/account-security.json +1 -1
  102. package/dist/registry/js-mongo-collection/admin-users.json +1 -1
  103. package/dist/registry/js-mongo-collection/auth.json +1 -1
  104. package/dist/registry/js-mongo-collection/auth@apple.json +1 -1
  105. package/dist/registry/js-mongo-collection/auth@google.json +1 -1
  106. package/dist/registry/js-mongo-collection/forgot-password.json +1 -1
  107. package/dist/registry/js-mongo-collection/user-profile.json +1 -1
  108. package/dist/registry/js-pg-model/account-security.json +1 -1
  109. package/dist/registry/js-pg-model/admin-users.json +1 -1
  110. package/dist/registry/js-pg-model/auth.json +1 -1
  111. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  112. package/dist/registry/js-pg-model/auth@google.json +1 -1
  113. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  114. package/dist/registry/js-pg-model/user-profile.json +1 -1
  115. package/dist/registry/js-pg-table/account-security.json +1 -1
  116. package/dist/registry/js-pg-table/admin-users.json +1 -1
  117. package/dist/registry/js-pg-table/auth.json +1 -1
  118. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  119. package/dist/registry/js-pg-table/auth@google.json +1 -1
  120. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  121. package/dist/registry/js-pg-table/user-profile.json +1 -1
  122. package/dist/registry/ts-mongo/account-security.json +1 -1
  123. package/dist/registry/ts-mongo/admin-users.json +1 -1
  124. package/dist/registry/ts-mongo/auth.json +1 -1
  125. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  126. package/dist/registry/ts-mongo/auth@google.json +1 -1
  127. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  128. package/dist/registry/ts-mongo/user-profile.json +1 -1
  129. package/dist/registry/ts-mongo-collection/account-security.json +1 -1
  130. package/dist/registry/ts-mongo-collection/admin-users.json +1 -1
  131. package/dist/registry/ts-mongo-collection/auth.json +1 -1
  132. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -1
  133. package/dist/registry/ts-mongo-collection/auth@google.json +1 -1
  134. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -1
  135. package/dist/registry/ts-mongo-collection/user-profile.json +1 -1
  136. package/dist/registry/ts-pg-model/account-security.json +1 -1
  137. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  138. package/dist/registry/ts-pg-model/auth.json +1 -1
  139. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  140. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  141. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  142. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  143. package/dist/registry/ts-pg-table/account-security.json +1 -1
  144. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  145. package/dist/registry/ts-pg-table/auth.json +1 -1
  146. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  147. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  148. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  149. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  150. package/dist/tasks/index.cjs +3 -2
  151. package/dist/tasks/index.cjs.map +1 -1
  152. package/dist/tasks/index.d.cts +1 -1
  153. package/dist/tasks/index.d.ts +1 -1
  154. package/dist/tasks/index.js +1 -1
  155. package/dist/testing-cjs.cjs +5 -0
  156. package/dist/testing.cjs +59 -0
  157. package/dist/testing.cjs.map +1 -0
  158. package/dist/testing.d.cts +27 -0
  159. package/dist/testing.d.ts +27 -0
  160. package/dist/testing.js +58 -0
  161. package/dist/testing.js.map +1 -0
  162. package/dist/thread-runner.cjs +4 -3
  163. package/dist/thread-runner.cjs.map +1 -1
  164. package/dist/thread-runner.js +2 -2
  165. package/dist/{types-Bnxvj3l0.d.ts → types-CPMFTVXm.d.cts} +8 -0
  166. package/dist/{types-Bnxvj3l0.d.cts → types-CPMFTVXm.d.ts} +8 -0
  167. package/package.json +6 -1
  168. package/dist/chunk-4DOHQU6I.cjs.map +0 -1
  169. package/dist/chunk-73XJUT2S.js.map +0 -1
  170. package/dist/chunk-7KC2H76D.js.map +0 -1
  171. package/dist/chunk-DUADUR6R.cjs.map +0 -1
  172. package/dist/chunk-EGSSZUVO.js.map +0 -1
  173. package/dist/chunk-HBCY7ILD.cjs.map +0 -1
  174. package/dist/chunk-KFVFP2Q7.cjs.map +0 -1
  175. package/dist/chunk-NKLOE4AK.cjs.map +0 -1
  176. package/dist/chunk-QDEDOHP7.js.map +0 -1
  177. package/dist/chunk-WBLUGOAG.cjs.map +0 -1
  178. package/dist/pgboss-backend-FW42SBSM.js +0 -14
  179. package/dist/pgboss-backend-RVHUBJTU.cjs +0 -14
  180. package/dist/pgboss-backend-RVHUBJTU.cjs.map +0 -1
  181. /package/dist/{chunk-R52CUEGT.js.map → chunk-3SWI46YK.js.map} +0 -0
  182. /package/dist/{chunk-NI2BNGGV.js.map → chunk-5LPRKZPB.js.map} +0 -0
  183. /package/dist/{chunk-RAB44UGX.js.map → chunk-B6MB6HEG.js.map} +0 -0
  184. /package/dist/{chunk-ATVD2HGC.js.map → chunk-C2FOZ7ME.js.map} +0 -0
  185. /package/dist/{chunk-R4XO4SVM.js.map → chunk-MUVO7MGS.js.map} +0 -0
  186. /package/dist/{pgboss-backend-FW42SBSM.js.map → pgboss-backend-4X2YT4RB.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-KFVFP2Q7.cjs","../src/auth/index.ts","../src/cache/index.ts","../src/cache/ipc.ts","../src/auth/password.ts"],"names":["pending","prefix","cluster"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF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AACmC,QAAA;AAC9C,QAAA;AACF,MAAA;AACF,IAAA;AAEsB,IAAA;AACoC,MAAA;AACD,MAAA;AACV,QAAA;AAC3C,QAAA;AACF,MAAA;AACF,IAAA;AAE+C,IAAA;AACE,IAAA;AAC5C,IAAA;AACC,EAAA;AACwC,IAAA;AAChD,EAAA;AACF;AAYiE;AACX,EAAA;AACpC,IAAA;AAC8C,IAAA;AACnB,MAAA;AACzC,IAAA;AACF,EAAA;AACyB,EAAA;AACW,EAAA;AACtC;ADmRoF;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-KFVFP2Q7.cjs","sourcesContent":[null,"import { randomUUID } from 'node:crypto';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { SignJWT, jwtVerify, type JWTPayload } from 'jose';\nimport type { AuthStrategy } from '../types.js';\nimport { setCurrentUser } from '../context.js';\nimport { isCacheConfigured, rawGet, rawSet, revocationFailureMode } from '../cache/index.js';\nimport { getLogger } from '../logger.js';\n\ninterface AuthConfig {\n secret: string;\n strategy: AuthStrategy;\n expiresIn: string;\n cookieDomain?: string | undefined;\n}\n\nlet _config: AuthConfig | null = null;\n\nexport function configureAuth(config: AuthConfig): void {\n _config = config;\n}\n\nfunction getConfig(): AuthConfig {\n if (!_config) throw new Error('[EFC] Auth not configured — pass jwtSecret to ignite()');\n return _config;\n}\n\n// Every token carries a unique `jti` (so one session can be revoked) and its issue\n// time in milliseconds, `efc_iat` (so \"revoke all sessions issued before now\" doesn't\n// also catch a token minted in the same second as the revocation).\nasync function sign(payload: Record<string, unknown>): Promise<string> {\n const { secret, expiresIn } = getConfig();\n return new SignJWT({ ...payload, efc_iat: Date.now() })\n .setProtectedHeader({ alg: 'HS256' })\n .setJti(randomUUID())\n .setIssuedAt()\n .setExpirationTime(expiresIn)\n .sign(new TextEncoder().encode(secret));\n}\n\n/**\n * Signs a JWT for `payload` and hands it to the client the configured way: `'http-only'`\n * sets the `efc_token` cookie and resolves `undefined`; `'bearer'` resolves the token for\n * the response body (no cookie). `res.json({ ...(token ? { token } : {}) })` works for both.\n */\nexport async function issueToken(\n res: Response,\n payload: Record<string, unknown>,\n): Promise<string | undefined> {\n const { cookieDomain, strategy } = getConfig();\n const token = await sign(payload);\n if (strategy !== 'http-only') return token;\n\n res.cookie('efc_token', token, {\n httpOnly: true,\n secure: process.env['NODE_ENV'] === 'production',\n sameSite: 'strict',\n ...(cookieDomain !== undefined && { domain: cookieDomain }),\n });\n return undefined;\n}\n\nexport function revokeToken(res: Response): void {\n res.clearCookie('efc_token');\n}\n\nexport async function signToken(payload: Record<string, unknown>): Promise<string> {\n return sign(payload);\n}\n\nfunction tokenFrom(req: Request): string | undefined {\n if (getConfig().strategy === 'http-only') {\n return (req as typeof req & { cookies?: Record<string, string> }).cookies?.['efc_token'];\n }\n const auth = req.headers['authorization'];\n return typeof auth === 'string' && auth.startsWith('Bearer ') ? auth.slice(7) : undefined;\n}\n\nasync function verify(token: string): Promise<JWTPayload> {\n // Only the algorithm EFC signs with — never whatever the token's header claims.\n const { payload } = await jwtVerify(token, new TextEncoder().encode(getConfig().secret), {\n algorithms: ['HS256'],\n });\n return payload;\n}\n\nconst userIdOf = (payload: JWTPayload): string | undefined => {\n const id = payload.sub ?? (payload as Record<string, unknown>)['id'];\n return id === undefined || id === null ? undefined : String(id);\n};\n\n// ── Session revocation (needs `cache` in ignite()) ───────────────────────────\n// Stateless JWTs can't be \"un-issued\", so revocation is a denylist in the cache:\n// one key per revoked token (`sess:jti:<jti>`, kept until that token would expire)\n// and one per user for \"everything issued before T\" (`sess:user:<id>`).\n\n/** Lifetime of a token signed now, in seconds — `jwtExpiresIn` like '15m', '7d'. */\nfunction tokenLifetimeSeconds(): number {\n const m =\n /^(\\d+(?:\\.\\d+)?)\\s*(s|sec|secs|seconds?|m|min|mins|minutes?|h|hr|hrs|hours?|d|days?|w|weeks?|y|yrs?|years?)?$/i.exec(\n getConfig().expiresIn.trim(),\n );\n if (!m) return 30 * 86_400;\n const n = Number(m[1]);\n const unit = (m[2] ?? 's')[0]!.toLowerCase();\n const factor = { s: 1, m: 60, h: 3600, d: 86_400, w: 604_800, y: 31_557_600 }[unit] ?? 1;\n return Math.ceil(n * factor);\n}\n\nlet lastRevocationError = 0;\n\nasync function isRevoked(payload: JWTPayload): Promise<boolean> {\n if (payload.jti && (await rawGet(`sess:jti:${payload.jti}`)) !== null) return true;\n const userId = userIdOf(payload);\n if (userId === undefined) return false;\n const cutoff = await rawGet(`sess:user:${userId}`);\n if (cutoff === null) return false;\n const issuedMs =\n typeof (payload as Record<string, unknown>)['efc_iat'] === 'number'\n ? ((payload as Record<string, unknown>)['efc_iat'] as number)\n : (payload.iat ?? 0) * 1000; // tokens minted before efc_iat existed\n return issuedMs < Number(cutoff);\n}\n\nfunction requireRevocationStore(): void {\n if (!isCacheConfigured()) {\n throw new Error(\n '[EFC] Session revocation needs a cache — pass cache: { backend: \"redis\" } to ignite()',\n );\n }\n}\n\n/**\n * Revokes the token the current request was authenticated with: `requireAuth` rejects\n * it from now until it would have expired anyway. Pass `res` to also clear the cookie\n * (http-only strategy). Throws if the cache is unreachable, so a failed logout is visible.\n */\nexport async function revokeSession(req: Request, res?: Response): Promise<void> {\n requireRevocationStore();\n const token = tokenFrom(req);\n if (res && getConfig().strategy === 'http-only') res.clearCookie('efc_token');\n if (!token) return;\n let payload: JWTPayload;\n try {\n payload = await verify(token);\n } catch {\n return; // already invalid or expired — nothing to revoke\n }\n if (!payload.jti) return;\n const ttl = payload.exp ? payload.exp - Math.floor(Date.now() / 1000) : tokenLifetimeSeconds();\n if (ttl > 0) await rawSet(`sess:jti:${payload.jti}`, '1', ttl);\n}\n\n/**\n * Revokes every token issued to `userId` (the JWT's `sub` or `id` claim) before now —\n * \"log out of all devices\", or after a password change. Tokens issued afterwards work.\n */\nexport async function revokeAllSessions(userId: string | number): Promise<void> {\n requireRevocationStore();\n await rawSet(`sess:user:${String(userId)}`, String(Date.now()), tokenLifetimeSeconds());\n}\n\nasync function authenticate(\n req: Request,\n res: Response,\n next: NextFunction,\n roles: string[],\n): Promise<void> {\n try {\n const token = tokenFrom(req);\n\n if (!token) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n\n const payload = await verify(token);\n\n if (isCacheConfigured()) {\n let revoked = false;\n try {\n revoked = await isRevoked(payload);\n } catch (err) {\n const reject = revocationFailureMode() === 'reject';\n if (Date.now() - lastRevocationError > 30_000) {\n lastRevocationError = Date.now();\n getLogger().error(\n { err },\n `Session revocation check failed — ${reject ? 'rejecting with 503' : 'allowing'} authenticated requests`,\n );\n }\n // 503, not 401: the session isn't invalid, the check is unavailable — clients\n // shouldn't discard the token and force a re-login over a cache blip.\n if (reject) {\n res.status(503).json({ error: 'Service Unavailable', statusCode: 503 });\n return;\n }\n }\n if (revoked) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n }\n\n if (roles.length > 0) {\n const role = (payload as Record<string, unknown>)['role'];\n if (typeof role !== 'string' || !roles.includes(role)) {\n res.status(403).json({ error: 'Forbidden' });\n return;\n }\n }\n\n (req as typeof req & { user: unknown }).user = payload;\n setCurrentUser(payload as Record<string, unknown>);\n next();\n } catch {\n res.status(401).json({ error: 'Unauthorized' });\n }\n}\n\n/**\n * Used bare (`middlewares = [requireAuth]`) it just verifies the JWT.\n * Called with role names (`middlewares = [requireAuth('admin')]`) it\n * returns a middleware that also enforces `payload.role` is one of them.\n */\nexport interface RequireAuth {\n (req: Request, res: Response, next: NextFunction): void;\n (...roles: string[]): RequestHandler;\n}\n\nexport const requireAuth: RequireAuth = ((...args: unknown[]) => {\n if (args.length > 0 && typeof args[0] === 'string') {\n const roles = args as string[];\n return (req: Request, res: Response, next: NextFunction) => {\n void authenticate(req, res, next, roles);\n };\n }\n const [req, res, next] = args as [Request, Response, NextFunction];\n void authenticate(req, res, next, []);\n}) as RequireAuth;\n\n// Reads the JWT payload requireAuth attached for the in-flight request, from\n// anywhere — not just where `req` is in scope. Returns undefined outside a\n// request, or on a request that never ran through requireAuth.\nexport { getCurrentUser } from '../context.js';\nexport { hashPassword, verifyPassword, passwordNeedsRehash } from './password.js';\n","import cluster from 'node:cluster';\nimport type { Redis as RedisClient, RedisOptions } from 'ioredis';\nimport type { CacheConfig } from '../types.js';\nimport { getLogger } from '../logger.js';\nimport { notInstalled } from '../db/postgres.js';\nimport { parseRedisUrl } from '../tasks/bullmq-backend.js';\nimport { connectPrimaryCache } from './ipc.js';\n\n// A small key/value cache with two backends:\n// - redis: shared by every worker and instance — what production wants.\n// - memory: in-process; under clustering the primary holds it and workers reach it\n// over IPC, so it's shared by all workers on the machine (not across machines).\n// Values are JSON-serialised. A Redis outage degrades to cache misses instead of\n// failing the request — a cache must never be the thing that takes the API down.\n\nexport interface Backend {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, ttlSeconds: number | undefined): Promise<void>;\n del(keys: string[]): Promise<number>;\n clear(prefix: string): Promise<number>;\n /**\n * Atomically adds 1 to an integer value (a missing key counts as 0). The TTL is set only\n * when the key is created, so it describes a fixed window. `ttlMs` is what's left of it\n * (null: no expiry).\n */\n incr(\n key: string,\n ttlSeconds: number | undefined,\n ): Promise<{ value: number; ttlMs: number | null }>;\n close(): Promise<void>;\n}\n\nexport function memoryBackend(maxEntries: number): Backend {\n const store = new Map<string, { value: string; expires: number }>();\n const live = (key: string) => {\n const hit = store.get(key);\n if (!hit) return undefined;\n if (hit.expires !== 0 && hit.expires <= Date.now()) {\n store.delete(key);\n return undefined;\n }\n return hit;\n };\n return {\n async get(key) {\n const hit = live(key);\n if (!hit) return null;\n // Re-insert so Map order tracks recency (LRU eviction drops the oldest).\n store.delete(key);\n store.set(key, hit);\n return hit.value;\n },\n async set(key, value, ttl) {\n store.delete(key);\n store.set(key, { value, expires: ttl ? Date.now() + ttl * 1000 : 0 });\n while (store.size > maxEntries) store.delete(store.keys().next().value!);\n },\n async del(keys) {\n let n = 0;\n for (const k of keys) if (live(k) && store.delete(k)) n++;\n return n;\n },\n async clear(prefix) {\n let n = 0;\n for (const k of [...store.keys()]) if (k.startsWith(prefix) && store.delete(k)) n++;\n return n;\n },\n // One event-loop turn, no awaits: atomic within this process. Under clustering this\n // store lives in the primary, so it's atomic across workers too.\n async incr(key, ttl) {\n const hit = live(key);\n const current = hit ? Number(hit.value) : 0;\n if (!Number.isInteger(current)) throw new Error(`cache incr: \"${key}\" is not an integer`);\n const expires = hit ? hit.expires : ttl ? Date.now() + ttl * 1000 : 0;\n store.delete(key);\n store.set(key, { value: String(current + 1), expires });\n while (store.size > maxEntries) store.delete(store.keys().next().value!);\n return {\n value: current + 1,\n ttlMs: expires === 0 ? null : Math.max(0, expires - Date.now()),\n };\n },\n async close() {\n store.clear();\n },\n };\n}\n\nasync function redisBackend(url: string, timeout: number): Promise<Backend> {\n let Redis: new (opts: RedisOptions) => RedisClient;\n try {\n const mod = (await import('ioredis')) as unknown as {\n Redis?: typeof Redis;\n default?: typeof Redis;\n };\n Redis = (mod.Redis ?? mod.default)!;\n } catch (err) {\n throw notInstalled(err, 'ioredis', 'npm install ioredis');\n }\n const client = new Redis({\n ...parseRedisUrl(url),\n // Fail fast instead of queueing commands while disconnected; callers treat\n // a rejected command as a miss.\n enableOfflineQueue: false,\n maxRetriesPerRequest: 1,\n commandTimeout: timeout,\n });\n let lastWarn = 0;\n client.on('error', (err: Error) => {\n // Reconnect attempts emit an error each time — log at most every 30 s.\n if (Date.now() - lastWarn > 30_000) {\n lastWarn = Date.now();\n getLogger().warn(`Cache Redis unavailable: ${err.message} (serving cache misses)`);\n }\n });\n\n // Wait for the first connection so writes made right after boot aren't dropped (the\n // offline queue is off), but never longer than a few timeouts: an unreachable Redis\n // must not block startup — the cache just serves misses until it comes back.\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, Math.max(2000, timeout * 2));\n client.once('ready', () => {\n clearTimeout(timer);\n resolve();\n });\n });\n return {\n get: (key) => client.get(key),\n async set(key, value, ttl) {\n if (ttl) await client.set(key, value, 'EX', Math.max(1, Math.ceil(ttl)));\n else await client.set(key, value);\n },\n del: (keys) => (keys.length ? client.del(...keys) : Promise.resolve(0)),\n // INCR and the first EXPIRE in one script: a crash in between can't leave a counter\n // that never expires.\n async incr(key, ttl) {\n const [value, pttl] = (await client.eval(\n `local n = redis.call('INCR', KEYS[1])\n if n == 1 and tonumber(ARGV[1]) > 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end\n return {n, redis.call('PTTL', KEYS[1])}`,\n 1,\n key,\n ttl ? Math.max(1, Math.ceil(ttl * 1000)) : 0,\n )) as [number, number];\n return { value, ttlMs: pttl < 0 ? null : pttl };\n },\n async clear(prefix) {\n let n = 0;\n let cursor = '0';\n const match = prefix.replace(/[*?[\\]\\\\]/g, '\\\\$&') + '*';\n do {\n const [next, keys] = await client.scan(cursor, 'MATCH', match, 'COUNT', 500);\n cursor = next;\n if (keys.length) n += await client.unlink(...keys);\n } while (cursor !== '0');\n return n;\n },\n async close() {\n await client.quit().catch(() => client.disconnect());\n },\n };\n}\n\nlet backend: Backend | null = null;\nlet prefix = 'efc:';\nlet revocationFailure: 'reject' | 'allow' = 'reject';\n\n/** How requireAuth should treat a failed revocation check — see CacheConfig. */\nexport function revocationFailureMode(): 'reject' | 'allow' {\n return revocationFailure;\n}\nconst pending = new Map<string, Promise<unknown>>();\n\nexport async function configureCache(config: CacheConfig): Promise<void> {\n await closeCache();\n prefix = config.prefix ?? 'efc:';\n revocationFailure = config.onRevocationCheckError ?? 'reject';\n if (config.backend === 'redis') {\n backend = await redisBackend(config.url ?? 'redis://localhost:6379', config.timeout ?? 1000);\n } else if (cluster.isWorker) {\n // Cluster workers share the primary's store over IPC (see cache/ipc.ts).\n backend = (await connectPrimaryCache()) ?? memoryBackend(config.maxEntries ?? 10_000);\n } else {\n backend = memoryBackend(config.maxEntries ?? 10_000);\n }\n}\n\nexport function isCacheConfigured(): boolean {\n return backend !== null;\n}\n\nexport async function closeCache(): Promise<void> {\n const b = backend;\n backend = null;\n pending.clear();\n await b?.close();\n}\n\nfunction requireBackend(): Backend {\n if (!backend) throw new Error('[EFC] Cache not configured — pass cache: { backend } to ignite()');\n return backend;\n}\n\n// Backend errors (Redis down/slow) degrade to \"no cache\" rather than failing the caller.\nasync function safely<T>(op: string, fn: (b: Backend) => Promise<T>, fallback: T): Promise<T> {\n const b = requireBackend();\n try {\n return await fn(b);\n } catch (err) {\n getLogger().debug({ err }, `cache ${op} failed`);\n return fallback;\n }\n}\n\nexport interface CacheSetOptions {\n /** Seconds until the entry expires. Omit for no expiry. */\n ttl?: number;\n}\n\nexport interface Cache {\n /** The cached value, or `undefined` on a miss (or when the backend is unreachable). */\n get<T = unknown>(key: string): Promise<T | undefined>;\n set(key: string, value: unknown, options?: CacheSetOptions): Promise<void>;\n has(key: string): Promise<boolean>;\n /** Deletes keys; returns how many existed. */\n del(...keys: string[]): Promise<number>;\n /**\n * Returns the cached value, or runs `fn`, caches its result and returns it.\n * Concurrent calls for the same key in one process share a single `fn` run.\n * `undefined` results are not cached.\n */\n wrap<T>(key: string, options: CacheSetOptions | number, fn: () => Promise<T>): Promise<T>;\n /** Deletes every key starting with `keyPrefix` (all of this app's keys when omitted). */\n clear(keyPrefix?: string): Promise<number>;\n /**\n * Atomically adds 1 and returns the new count — across workers and instances (Redis) or\n * this machine's workers (memory). `ttl` applies when the key is created (a fixed\n * window). Resolves `undefined` when the backend is unreachable: a count can't be made up.\n */\n incr(key: string, options?: CacheSetOptions): Promise<number | undefined>;\n}\n\nexport const cache: Cache = {\n async get<T>(key: string) {\n const raw = await safely('get', (b) => b.get(prefix + key), null);\n return raw === null ? undefined : (JSON.parse(raw) as T);\n },\n async set(key, value, options) {\n if (value === undefined) return;\n await safely('set', (b) => b.set(prefix + key, JSON.stringify(value), options?.ttl), undefined);\n },\n async has(key) {\n return (await safely('get', (b) => b.get(prefix + key), null)) !== null;\n },\n async del(...keys) {\n return safely('del', (b) => b.del(keys.map((k) => prefix + k)), 0);\n },\n async wrap<T>(key: string, options: CacheSetOptions | number, fn: () => Promise<T>) {\n const hit = await cache.get<T>(key);\n if (hit !== undefined) return hit;\n const inflight = pending.get(key) as Promise<T> | undefined;\n if (inflight) return inflight;\n const run = (async () => {\n try {\n const value = await fn();\n await cache.set(key, value, typeof options === 'number' ? { ttl: options } : options);\n return value;\n } finally {\n pending.delete(key);\n }\n })();\n pending.set(key, run);\n return run;\n },\n async clear(keyPrefix = '') {\n return safely('clear', (b) => b.clear(prefix + keyPrefix), 0);\n },\n async incr(key, options) {\n const r = await safely('incr', (b) => b.incr(prefix + key, options?.ttl), undefined);\n return r?.value;\n },\n};\n\n/** For rateLimit: the count and the window's remaining time; throws when the backend is down. */\nexport async function rawIncr(\n key: string,\n ttlSeconds: number,\n): Promise<{ value: number; ttlMs: number | null }> {\n return requireBackend().incr(prefix + key, ttlSeconds);\n}\n\n/** For auth's revocation checks, which must distinguish \"absent\" from \"backend down\". */\nexport async function rawGet(key: string): Promise<string | null> {\n return requireBackend().get(prefix + key);\n}\n\nexport async function rawSet(key: string, value: string, ttlSeconds: number): Promise<void> {\n await requireBackend().set(prefix + key, value, ttlSeconds);\n}\n","import cluster, { type Worker } from 'node:cluster';\nimport { randomUUID } from 'node:crypto';\nimport type { Backend } from './index.js';\nimport { memoryBackend } from './index.js';\nimport { getLogger } from '../logger.js';\n\n// The memory cache under clustering: the primary owns the only store and answers\n// workers' requests over the cluster IPC channel, so every worker sees the same\n// entries and the same revoked sessions. Message shape is tagged to avoid clashing\n// with application IPC.\n\nconst TAG = '__efcCache';\nconst TIMEOUT_MS = 2000;\n\ntype Op = 'ping' | 'get' | 'set' | 'del' | 'clear' | 'incr';\ninterface Request {\n [TAG]: true;\n id: string;\n op: Op;\n args: unknown[];\n}\ninterface Response {\n [TAG]: true;\n id: string;\n ok: boolean;\n result?: unknown;\n error?: string;\n}\n\nconst isTagged = (msg: unknown): msg is Record<string, unknown> =>\n msg !== null && typeof msg === 'object' && (msg as Record<string, unknown>)[TAG] === true;\n\n/** Primary side: hold the store and serve every worker. Called before workers fork. */\nexport function servePrimaryCache(maxEntries: number): void {\n const store = memoryBackend(maxEntries);\n cluster.on('message', (worker: Worker, msg: unknown) => {\n if (!isTagged(msg)) return;\n const req = msg as unknown as Request;\n const run = async (): Promise<unknown> => {\n switch (req.op) {\n case 'ping':\n return 'pong';\n case 'get':\n return store.get(req.args[0] as string);\n case 'set':\n return store.set(\n req.args[0] as string,\n req.args[1] as string,\n req.args[2] as number | undefined,\n );\n case 'del':\n return store.del(req.args[0] as string[]);\n case 'clear':\n return store.clear(req.args[0] as string);\n case 'incr':\n return store.incr(req.args[0] as string, req.args[1] as number | undefined);\n }\n };\n run().then(\n (result) =>\n worker.isConnected() &&\n worker.send({ [TAG]: true, id: req.id, ok: true, result } satisfies Response),\n (err: unknown) =>\n worker.isConnected() &&\n worker.send({ [TAG]: true, id: req.id, ok: false, error: String(err) } satisfies Response),\n );\n });\n}\n\n/**\n * Worker side: a Backend that forwards to the primary. Resolves to null — so the caller\n * can fall back to a local store — when no EFC primary answers (e.g. the app runs its\n * own cluster primary instead of ignite()'s).\n */\nexport async function connectPrimaryCache(): Promise<Backend | null> {\n if (!process.send) return null;\n const pending = new Map<\n string,\n { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }\n >();\n const onMessage = (msg: unknown) => {\n if (!isTagged(msg)) return;\n const res = msg as unknown as Response;\n const p = pending.get(res.id);\n if (!p) return;\n pending.delete(res.id);\n clearTimeout(p.timer);\n if (res.ok) p.resolve(res.result);\n else p.reject(new Error(res.error));\n };\n process.on('message', onMessage);\n\n const call = (op: Op, ...args: unknown[]) =>\n new Promise<unknown>((resolve, reject) => {\n const id = randomUUID();\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(new Error(`[EFC] cache IPC \"${op}\" timed out`));\n }, TIMEOUT_MS);\n timer.unref();\n pending.set(id, { resolve, reject, timer });\n process.send!({ [TAG]: true, id, op, args } satisfies Request);\n });\n\n try {\n await call('ping');\n } catch {\n process.off('message', onMessage);\n getLogger().warn(\n 'cache backend \"memory\": no EFC cluster primary answered — using a per-worker store (entries and revoked sessions are not shared)',\n );\n return null;\n }\n\n return {\n get: async (key) => (await call('get', key)) as string | null,\n set: async (key, value, ttl) => {\n await call('set', key, value, ttl);\n },\n del: async (keys) => (await call('del', keys)) as number,\n clear: async (prefix) => (await call('clear', prefix)) as number,\n incr: async (key, ttl) =>\n (await call('incr', key, ttl)) as { value: number; ttlMs: number | null },\n close: async () => {\n process.off('message', onMessage);\n for (const p of pending.values()) clearTimeout(p.timer);\n pending.clear();\n },\n };\n}\n","import { randomBytes, scrypt, timingSafeEqual, type ScryptOptions } from 'node:crypto';\nimport { getLogger } from '../logger.js';\n\n// Password hashing on node:crypto's scrypt — no native addon, no extra dependency.\n// Stored format: `scrypt$<N>$<r>$<p>$<salt b64>$<key b64>`. The cost parameters travel\n// with each hash, so raising them later doesn't invalidate passwords already stored.\n// N=2^15, r=8, p=1: 32 MiB and ~100–250 ms per hash — above bcrypt cost 10 (what EFC used before)\n// without making each login hold a libuv thread for most of a second.\nconst N = 2 ** 15;\nconst R = 8;\nconst P = 1;\nconst KEY_LEN = 64;\nconst SALT_LEN = 16;\n\nfunction derive(\n password: string,\n salt: Buffer,\n n: number,\n r: number,\n p: number,\n keyLen: number,\n): Promise<Buffer> {\n // scrypt needs 128 * N * r bytes; Node's default maxmem (32 MiB) is exactly that at our defaults.\n const options: ScryptOptions = { N: n, r, p, maxmem: 256 * n * r };\n return new Promise((resolve, reject) => {\n scrypt(password.normalize('NFKC'), salt, keyLen, options, (err, key) =>\n err ? reject(err) : resolve(key),\n );\n });\n}\n\n/** Hashes a password with scrypt and a random salt. Store the returned string as-is. */\nexport async function hashPassword(password: string): Promise<string> {\n if (typeof password !== 'string' || password.length === 0) {\n throw new TypeError('[EFC] hashPassword: password must be a non-empty string');\n }\n const salt = randomBytes(SALT_LEN);\n const key = await derive(password, salt, N, R, P, KEY_LEN);\n return `scrypt$${N}$${R}$${P}$${salt.toString('base64')}$${key.toString('base64')}`;\n}\n\n/**\n * Checks a password against a hash from `hashPassword`. Returns false for a wrong password or any\n * other format — including bcrypt hashes (`$2a$`/`$2b$`/`$2y$`) from apps scaffolded before 0.9.2,\n * which EFC deliberately can't verify: those accounts reset their password.\n */\nexport async function verifyPassword(password: string, hash: string): Promise<boolean> {\n if (typeof password !== 'string' || typeof hash !== 'string') return false;\n if (/^\\$2[aby]\\$/.test(hash)) {\n getLogger().warn(\n '[EFC] verifyPassword: bcrypt hash found — not supported since 0.9.2. ' +\n 'This account must reset its password (the reset stores a hashPassword() hash).',\n );\n return false;\n }\n\n const parts = hash.split('$');\n if (parts.length !== 6 || parts[0] !== 'scrypt') return false;\n const [n, r, p] = parts.slice(1, 4).map(Number) as [number, number, number];\n if (![n, r, p].every((v) => Number.isInteger(v) && v > 0) || (n & (n - 1)) !== 0) return false;\n // Refuse cost parameters far above ours — a planted hash shouldn't be able to pin a worker.\n if (n > 2 ** 20 || r > 32 || p > 16) return false;\n const salt = Buffer.from(parts[4]!, 'base64');\n const expected = Buffer.from(parts[5]!, 'base64');\n if (salt.length === 0 || expected.length === 0) return false;\n\n const actual = await derive(password, salt, n, r, p, expected.length);\n return timingSafeEqual(actual, expected);\n}\n\n/** True when a stored hash should be replaced with `hashPassword()` (e.g. after a successful login). */\nexport function passwordNeedsRehash(hash: string): boolean {\n return !hash.startsWith(`scrypt$${N}$${R}$${P}$`);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-NKLOE4AK.cjs","../src/errors.ts","../src/db/schema.ts","../src/db/engine.ts","../src/db/pg-table.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACKO,IAAM,UAAA,EAAN,MAAM,WAAA,QAAkB,MAAM;AAAA,EAC1B;AAAA,EAET,WAAA,CA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AAA;AAEsB,EAAA;AACU,IAAA;AACyB,IAAA;AACzD,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;AJkH4D;AACA;AACA;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-NKLOE4AK.cjs","sourcesContent":[null,"/**\n * Represents an HTTP error with a status code and message.\n * Throw this inside any route handler to send a structured error response.\n *\n * @example\n * throw new HttpError(404, 'User not found');\n *\n * @example Wrapping an unknown caught error\n * catch (err) {\n * throw HttpError.from(err, 500);\n * }\n */\nexport class HttpError extends Error {\n readonly statusCode: number;\n\n constructor(statusCode: number, message: string) {\n super(message);\n this.name = 'HttpError';\n this.statusCode = statusCode;\n Error.captureStackTrace(this, HttpError);\n }\n\n /**\n * Wraps an unknown caught value into an `HttpError`.\n * If the value is already an `HttpError`, it is returned as-is.\n * Otherwise the `message` from the caught `Error` (or a fallback) is used.\n *\n * @example\n * } catch (err) {\n * throw HttpError.from(err, 500, 'Something went wrong');\n * }\n */\n static from(err: unknown, statusCode = 500, fallback = 'Internal Server Error'): HttpError {\n if (err instanceof HttpError) return err;\n const message = err instanceof Error ? err.message : fallback;\n return new HttpError(statusCode, message);\n }\n\n /** Returns a plain object representation suitable for JSON serialization. */\n toJSON(): { statusCode: number; error: string; message: string } {\n return {\n statusCode: this.statusCode,\n error: this.name,\n message: this.message,\n };\n }\n}\n\n/**\n * Type guard — returns `true` when `value` is an `HttpError` instance.\n *\n * @example\n * if (isHttpError(err)) console.log(err.statusCode);\n */\nexport function isHttpError(value: unknown): value is HttpError {\n return value instanceof HttpError;\n}\n","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 { 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) {\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 }\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"]}