@opensaas/stack-core 0.43.0 → 0.44.0-alpha.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 (641) hide show
  1. package/CHANGELOG.md +2753 -0
  2. package/README.md +182 -115
  3. package/dist/.build-hash +1 -0
  4. package/dist/access/declared-dependencies.d.ts +102 -88
  5. package/dist/access/declared-dependencies.d.ts.map +1 -1
  6. package/dist/access/declared-dependencies.js +83 -71
  7. package/dist/access/declared-dependencies.js.map +1 -1
  8. package/dist/access/depth-limits.d.ts +4 -0
  9. package/dist/access/depth-limits.d.ts.map +1 -1
  10. package/dist/access/depth-limits.js +4 -0
  11. package/dist/access/depth-limits.js.map +1 -1
  12. package/dist/access/engine.d.ts +68 -20
  13. package/dist/access/engine.d.ts.map +1 -1
  14. package/dist/access/engine.js +151 -37
  15. package/dist/access/engine.js.map +1 -1
  16. package/dist/access/errors.d.ts +33 -48
  17. package/dist/access/errors.d.ts.map +1 -1
  18. package/dist/access/errors.js +73 -63
  19. package/dist/access/errors.js.map +1 -1
  20. package/dist/access/field-access.d.ts +76 -5
  21. package/dist/access/field-access.d.ts.map +1 -1
  22. package/dist/access/field-access.js +235 -61
  23. package/dist/access/field-access.js.map +1 -1
  24. package/dist/access/field-visibility.d.ts +50 -4
  25. package/dist/access/field-visibility.d.ts.map +1 -1
  26. package/dist/access/field-visibility.js +143 -160
  27. package/dist/access/field-visibility.js.map +1 -1
  28. package/dist/access/index.d.ts +5 -12
  29. package/dist/access/index.d.ts.map +1 -1
  30. package/dist/access/index.js +6 -19
  31. package/dist/access/index.js.map +1 -1
  32. package/dist/access/orm-client.d.ts +19 -0
  33. package/dist/access/orm-client.d.ts.map +1 -0
  34. package/dist/access/orm-client.js +37 -0
  35. package/dist/access/orm-client.js.map +1 -0
  36. package/dist/access/query-validation.d.ts +7 -129
  37. package/dist/access/query-validation.d.ts.map +1 -1
  38. package/dist/access/query-validation.js +12 -314
  39. package/dist/access/query-validation.js.map +1 -1
  40. package/dist/access/system-fields.d.ts +2 -0
  41. package/dist/access/system-fields.d.ts.map +1 -0
  42. package/dist/access/system-fields.js +7 -0
  43. package/dist/access/system-fields.js.map +1 -0
  44. package/dist/access/transaction-registry.d.ts +25 -2
  45. package/dist/access/transaction-registry.d.ts.map +1 -1
  46. package/dist/access/transaction-registry.js +34 -17
  47. package/dist/access/transaction-registry.js.map +1 -1
  48. package/dist/access/types.d.ts +217 -131
  49. package/dist/access/types.d.ts.map +1 -1
  50. package/dist/config/field-kind.d.ts +66 -0
  51. package/dist/config/field-kind.d.ts.map +1 -0
  52. package/dist/config/field-kind.js +63 -0
  53. package/dist/config/field-kind.js.map +1 -0
  54. package/dist/config/hook-only-fields.d.ts +3 -0
  55. package/dist/config/hook-only-fields.d.ts.map +1 -0
  56. package/dist/config/hook-only-fields.js +17 -0
  57. package/dist/config/hook-only-fields.js.map +1 -0
  58. package/dist/config/index.d.ts +3 -1
  59. package/dist/config/index.d.ts.map +1 -1
  60. package/dist/config/index.js +6 -3
  61. package/dist/config/index.js.map +1 -1
  62. package/dist/config/mcp-tool-names.d.ts +3 -0
  63. package/dist/config/mcp-tool-names.d.ts.map +1 -0
  64. package/dist/config/mcp-tool-names.js +25 -0
  65. package/dist/config/mcp-tool-names.js.map +1 -0
  66. package/dist/config/nav-count.d.ts.map +1 -1
  67. package/dist/config/nav-count.js +4 -4
  68. package/dist/config/nav-count.js.map +1 -1
  69. package/dist/config/plugin-engine.d.ts +8 -2
  70. package/dist/config/plugin-engine.d.ts.map +1 -1
  71. package/dist/config/plugin-engine.js +102 -38
  72. package/dist/config/plugin-engine.js.map +1 -1
  73. package/dist/config/types.d.ts +1035 -611
  74. package/dist/config/types.d.ts.map +1 -1
  75. package/dist/context/apply-defaults.d.ts +18 -1
  76. package/dist/context/apply-defaults.d.ts.map +1 -1
  77. package/dist/context/apply-defaults.js +30 -4
  78. package/dist/context/apply-defaults.js.map +1 -1
  79. package/dist/context/engine-context.d.ts +73 -0
  80. package/dist/context/engine-context.d.ts.map +1 -0
  81. package/dist/context/engine-context.js +67 -0
  82. package/dist/context/engine-context.js.map +1 -0
  83. package/dist/context/hook-pipeline.d.ts +9 -2
  84. package/dist/context/hook-pipeline.d.ts.map +1 -1
  85. package/dist/context/hook-pipeline.js +5 -4
  86. package/dist/context/hook-pipeline.js.map +1 -1
  87. package/dist/context/index.d.ts +98 -89
  88. package/dist/context/index.d.ts.map +1 -1
  89. package/dist/context/index.js +917 -722
  90. package/dist/context/index.js.map +1 -1
  91. package/dist/context/junction.d.ts +59 -0
  92. package/dist/context/junction.d.ts.map +1 -0
  93. package/dist/context/junction.js +126 -0
  94. package/dist/context/junction.js.map +1 -0
  95. package/dist/context/plugin-field-read.d.ts +33 -0
  96. package/dist/context/plugin-field-read.d.ts.map +1 -0
  97. package/dist/context/plugin-field-read.js +41 -0
  98. package/dist/context/plugin-field-read.js.map +1 -0
  99. package/dist/context/plugin-field-write.d.ts +104 -0
  100. package/dist/context/plugin-field-write.d.ts.map +1 -0
  101. package/dist/context/plugin-field-write.js +184 -0
  102. package/dist/context/plugin-field-write.js.map +1 -0
  103. package/dist/context/relationship-input.d.ts +146 -0
  104. package/dist/context/relationship-input.d.ts.map +1 -0
  105. package/dist/context/relationship-input.js +453 -0
  106. package/dist/context/relationship-input.js.map +1 -0
  107. package/dist/context/transaction-boundary.d.ts +54 -28
  108. package/dist/context/transaction-boundary.d.ts.map +1 -1
  109. package/dist/context/transaction-boundary.js +87 -169
  110. package/dist/context/transaction-boundary.js.map +1 -1
  111. package/dist/context/write-pipeline.d.ts +33 -51
  112. package/dist/context/write-pipeline.d.ts.map +1 -1
  113. package/dist/context/write-pipeline.js +372 -185
  114. package/dist/context/write-pipeline.js.map +1 -1
  115. package/dist/contract/dependencies.d.ts +88 -0
  116. package/dist/contract/dependencies.d.ts.map +1 -0
  117. package/dist/contract/dependencies.js +237 -0
  118. package/dist/contract/dependencies.js.map +1 -0
  119. package/dist/contract/derive.d.ts +49 -0
  120. package/dist/contract/derive.d.ts.map +1 -0
  121. package/dist/contract/derive.js +629 -0
  122. package/dist/contract/derive.js.map +1 -0
  123. package/dist/contract/fixtures/contract-configs.d.ts +64 -0
  124. package/dist/contract/fixtures/contract-configs.d.ts.map +1 -0
  125. package/dist/contract/fixtures/contract-configs.js +345 -0
  126. package/dist/contract/fixtures/contract-configs.js.map +1 -0
  127. package/dist/contract/id-boundary.d.ts +53 -0
  128. package/dist/contract/id-boundary.d.ts.map +1 -0
  129. package/dist/contract/id-boundary.js +76 -0
  130. package/dist/contract/id-boundary.js.map +1 -0
  131. package/dist/contract/index.d.ts +8 -0
  132. package/dist/contract/index.d.ts.map +1 -0
  133. package/dist/contract/index.js +11 -0
  134. package/dist/contract/index.js.map +1 -0
  135. package/dist/contract/prisma.d.ts +58 -0
  136. package/dist/contract/prisma.d.ts.map +1 -0
  137. package/dist/contract/prisma.js +294 -0
  138. package/dist/contract/prisma.js.map +1 -0
  139. package/dist/contract/relation-graph.d.ts +70 -0
  140. package/dist/contract/relation-graph.d.ts.map +1 -0
  141. package/dist/contract/relation-graph.js +113 -0
  142. package/dist/contract/relation-graph.js.map +1 -0
  143. package/dist/contract/types.d.ts +153 -0
  144. package/dist/contract/types.d.ts.map +1 -0
  145. package/dist/contract/types.js +2 -0
  146. package/dist/contract/types.js.map +1 -0
  147. package/dist/db/client.d.ts +55 -0
  148. package/dist/db/client.d.ts.map +1 -0
  149. package/dist/db/client.js +73 -0
  150. package/dist/db/client.js.map +1 -0
  151. package/dist/db/dev-database.d.ts +124 -0
  152. package/dist/db/dev-database.d.ts.map +1 -0
  153. package/dist/db/dev-database.js +291 -0
  154. package/dist/db/dev-database.js.map +1 -0
  155. package/dist/db/password-front.d.ts +10 -0
  156. package/dist/db/password-front.d.ts.map +1 -0
  157. package/dist/db/password-front.js +147 -0
  158. package/dist/db/password-front.js.map +1 -0
  159. package/dist/db/process-identity.d.ts +36 -0
  160. package/dist/db/process-identity.d.ts.map +1 -0
  161. package/dist/db/process-identity.js +114 -0
  162. package/dist/db/process-identity.js.map +1 -0
  163. package/dist/db/state-file.d.ts +54 -0
  164. package/dist/db/state-file.d.ts.map +1 -0
  165. package/dist/db/state-file.js +91 -0
  166. package/dist/db/state-file.js.map +1 -0
  167. package/dist/db/url.d.ts +89 -0
  168. package/dist/db/url.d.ts.map +1 -0
  169. package/dist/db/url.js +118 -0
  170. package/dist/db/url.js.map +1 -0
  171. package/dist/extend.d.ts +13 -2
  172. package/dist/extend.d.ts.map +1 -1
  173. package/dist/extend.js +24 -1
  174. package/dist/extend.js.map +1 -1
  175. package/dist/fields/index.d.ts +87 -42
  176. package/dist/fields/index.d.ts.map +1 -1
  177. package/dist/fields/index.js +462 -678
  178. package/dist/fields/index.js.map +1 -1
  179. package/dist/filter/collect.d.ts +3 -4
  180. package/dist/filter/collect.d.ts.map +1 -1
  181. package/dist/filter/collect.js +2 -2
  182. package/dist/filter/collect.js.map +1 -1
  183. package/dist/filter/index.d.ts +1 -2
  184. package/dist/filter/index.d.ts.map +1 -1
  185. package/dist/filter/index.js +0 -1
  186. package/dist/filter/index.js.map +1 -1
  187. package/dist/filter/map.d.ts +12 -5
  188. package/dist/filter/map.d.ts.map +1 -1
  189. package/dist/filter/map.js +47 -19
  190. package/dist/filter/map.js.map +1 -1
  191. package/dist/filter/types.d.ts +10 -24
  192. package/dist/filter/types.d.ts.map +1 -1
  193. package/dist/filter/types.js +2 -11
  194. package/dist/filter/types.js.map +1 -1
  195. package/dist/hooks/index.d.ts +22 -31
  196. package/dist/hooks/index.d.ts.map +1 -1
  197. package/dist/hooks/index.js +33 -37
  198. package/dist/hooks/index.js.map +1 -1
  199. package/dist/hooks/transition-guard.d.ts +61 -0
  200. package/dist/hooks/transition-guard.d.ts.map +1 -0
  201. package/dist/hooks/transition-guard.js +93 -0
  202. package/dist/hooks/transition-guard.js.map +1 -0
  203. package/dist/index.d.ts +52 -16
  204. package/dist/index.d.ts.map +1 -1
  205. package/dist/index.js +105 -51
  206. package/dist/index.js.map +1 -1
  207. package/dist/internal.d.ts +4 -2
  208. package/dist/internal.d.ts.map +1 -1
  209. package/dist/internal.js +16 -0
  210. package/dist/internal.js.map +1 -1
  211. package/dist/lib/case-utils.d.ts +0 -1
  212. package/dist/lib/case-utils.d.ts.map +1 -1
  213. package/dist/lib/case-utils.js +0 -3
  214. package/dist/lib/case-utils.js.map +1 -1
  215. package/dist/lib/client-safe-error.d.ts +9 -0
  216. package/dist/lib/client-safe-error.d.ts.map +1 -0
  217. package/dist/lib/client-safe-error.js +23 -0
  218. package/dist/lib/client-safe-error.js.map +1 -0
  219. package/dist/lib/database-errors.d.ts +78 -0
  220. package/dist/lib/database-errors.d.ts.map +1 -0
  221. package/dist/lib/database-errors.js +148 -0
  222. package/dist/lib/database-errors.js.map +1 -0
  223. package/dist/lib/null-prototype-registry.d.ts +9 -0
  224. package/dist/lib/null-prototype-registry.d.ts.map +1 -0
  225. package/dist/lib/null-prototype-registry.js +11 -0
  226. package/dist/lib/null-prototype-registry.js.map +1 -0
  227. package/dist/lib/prisma-errors.d.ts +30 -32
  228. package/dist/lib/prisma-errors.d.ts.map +1 -1
  229. package/dist/lib/prisma-errors.js +86 -46
  230. package/dist/lib/prisma-errors.js.map +1 -1
  231. package/dist/lib/process-global.d.ts +23 -0
  232. package/dist/lib/process-global.d.ts.map +1 -0
  233. package/dist/lib/process-global.js +33 -0
  234. package/dist/lib/process-global.js.map +1 -0
  235. package/dist/lib/warn-once.d.ts +7 -0
  236. package/dist/lib/warn-once.d.ts.map +1 -0
  237. package/dist/lib/warn-once.js +13 -0
  238. package/dist/lib/warn-once.js.map +1 -0
  239. package/dist/mcp/advertise.d.ts +16 -0
  240. package/dist/mcp/advertise.d.ts.map +1 -0
  241. package/dist/mcp/advertise.js +25 -0
  242. package/dist/mcp/advertise.js.map +1 -0
  243. package/dist/mcp/arguments.d.ts +10 -0
  244. package/dist/mcp/arguments.d.ts.map +1 -0
  245. package/dist/mcp/arguments.js +143 -0
  246. package/dist/mcp/arguments.js.map +1 -0
  247. package/dist/mcp/field-schema.d.ts +50 -5
  248. package/dist/mcp/field-schema.d.ts.map +1 -1
  249. package/dist/mcp/field-schema.js +137 -14
  250. package/dist/mcp/field-schema.js.map +1 -1
  251. package/dist/mcp/handler.d.ts +16 -5
  252. package/dist/mcp/handler.d.ts.map +1 -1
  253. package/dist/mcp/handler.js +404 -126
  254. package/dist/mcp/handler.js.map +1 -1
  255. package/dist/mcp/index.d.ts +1 -0
  256. package/dist/mcp/index.d.ts.map +1 -1
  257. package/dist/mcp/index.js +1 -0
  258. package/dist/mcp/index.js.map +1 -1
  259. package/dist/mcp/projection.d.ts +42 -34
  260. package/dist/mcp/projection.d.ts.map +1 -1
  261. package/dist/mcp/projection.js +246 -200
  262. package/dist/mcp/projection.js.map +1 -1
  263. package/dist/mcp/tool-error.d.ts +8 -0
  264. package/dist/mcp/tool-error.d.ts.map +1 -0
  265. package/dist/mcp/tool-error.js +11 -0
  266. package/dist/mcp/tool-error.js.map +1 -0
  267. package/dist/mcp/types.d.ts +3 -2
  268. package/dist/mcp/types.d.ts.map +1 -1
  269. package/dist/mcp/where-id-boundary.d.ts +28 -0
  270. package/dist/mcp/where-id-boundary.d.ts.map +1 -0
  271. package/dist/mcp/where-id-boundary.js +187 -0
  272. package/dist/mcp/where-id-boundary.js.map +1 -0
  273. package/dist/origin.d.ts +147 -0
  274. package/dist/origin.d.ts.map +1 -0
  275. package/dist/origin.js +191 -0
  276. package/dist/origin.js.map +1 -0
  277. package/dist/query/relationship-options.d.ts +35 -6
  278. package/dist/query/relationship-options.d.ts.map +1 -1
  279. package/dist/query/relationship-options.js +33 -23
  280. package/dist/query/relationship-options.js.map +1 -1
  281. package/dist/secured/aggregate.d.ts +32 -0
  282. package/dist/secured/aggregate.d.ts.map +1 -0
  283. package/dist/secured/aggregate.js +31 -0
  284. package/dist/secured/aggregate.js.map +1 -0
  285. package/dist/secured/include.d.ts +320 -0
  286. package/dist/secured/include.d.ts.map +1 -0
  287. package/dist/secured/include.js +650 -0
  288. package/dist/secured/include.js.map +1 -0
  289. package/dist/secured/lock.d.ts +127 -0
  290. package/dist/secured/lock.d.ts.map +1 -0
  291. package/dist/secured/lock.js +275 -0
  292. package/dist/secured/lock.js.map +1 -0
  293. package/dist/secured/lower.d.ts +82 -0
  294. package/dist/secured/lower.d.ts.map +1 -0
  295. package/dist/secured/lower.js +162 -0
  296. package/dist/secured/lower.js.map +1 -0
  297. package/dist/secured/operators.d.ts +7 -0
  298. package/dist/secured/operators.d.ts.map +1 -0
  299. package/dist/secured/operators.js +18 -0
  300. package/dist/secured/operators.js.map +1 -0
  301. package/dist/secured/read.d.ts +208 -0
  302. package/dist/secured/read.d.ts.map +1 -0
  303. package/dist/secured/read.js +1245 -0
  304. package/dist/secured/read.js.map +1 -0
  305. package/dist/secured/select.d.ts +87 -0
  306. package/dist/secured/select.d.ts.map +1 -0
  307. package/dist/secured/select.js +250 -0
  308. package/dist/secured/select.js.map +1 -0
  309. package/dist/secured/vector.d.ts +58 -0
  310. package/dist/secured/vector.d.ts.map +1 -0
  311. package/dist/secured/vector.js +113 -0
  312. package/dist/secured/vector.js.map +1 -0
  313. package/dist/secured/vocabulary.d.ts +227 -0
  314. package/dist/secured/vocabulary.d.ts.map +1 -0
  315. package/dist/secured/vocabulary.js +578 -0
  316. package/dist/secured/vocabulary.js.map +1 -0
  317. package/dist/secured/write.d.ts +58 -0
  318. package/dist/secured/write.d.ts.map +1 -0
  319. package/dist/secured/write.js +87 -0
  320. package/dist/secured/write.js.map +1 -0
  321. package/dist/testing/context.d.ts +236 -0
  322. package/dist/testing/context.d.ts.map +1 -0
  323. package/dist/testing/context.js +457 -0
  324. package/dist/testing/context.js.map +1 -0
  325. package/dist/testing/escape.d.ts +83 -0
  326. package/dist/testing/escape.d.ts.map +1 -0
  327. package/dist/testing/escape.js +148 -0
  328. package/dist/testing/escape.js.map +1 -0
  329. package/dist/testing/extensions.d.ts +48 -0
  330. package/dist/testing/extensions.d.ts.map +1 -0
  331. package/dist/testing/extensions.js +107 -0
  332. package/dist/testing/extensions.js.map +1 -0
  333. package/dist/testing/index.d.ts +5 -0
  334. package/dist/testing/index.d.ts.map +1 -0
  335. package/dist/testing/index.js +11 -0
  336. package/dist/testing/index.js.map +1 -0
  337. package/dist/testing/plans.d.ts +64 -0
  338. package/dist/testing/plans.d.ts.map +1 -0
  339. package/dist/testing/plans.js +47 -0
  340. package/dist/testing/plans.js.map +1 -0
  341. package/dist/types/context.d.ts +110 -0
  342. package/dist/types/context.d.ts.map +1 -0
  343. package/dist/types/context.js +2 -0
  344. package/dist/types/context.js.map +1 -0
  345. package/dist/types/contract.d.ts +198 -0
  346. package/dist/types/contract.d.ts.map +1 -0
  347. package/dist/types/contract.js +2 -0
  348. package/dist/types/contract.js.map +1 -0
  349. package/dist/types/index.d.ts +6 -0
  350. package/dist/types/index.d.ts.map +1 -0
  351. package/dist/types/index.js +11 -0
  352. package/dist/types/index.js.map +1 -0
  353. package/dist/types/inputs.d.ts +83 -0
  354. package/dist/types/inputs.d.ts.map +1 -0
  355. package/dist/types/inputs.js +2 -0
  356. package/dist/types/inputs.js.map +1 -0
  357. package/dist/types/rows.d.ts +76 -0
  358. package/dist/types/rows.d.ts.map +1 -0
  359. package/dist/types/rows.js +2 -0
  360. package/dist/types/rows.js.map +1 -0
  361. package/dist/types/secured-list.d.ts +396 -0
  362. package/dist/types/secured-list.d.ts.map +1 -0
  363. package/dist/types/secured-list.js +2 -0
  364. package/dist/types/secured-list.js.map +1 -0
  365. package/dist/unsafe.d.ts +162 -0
  366. package/dist/unsafe.d.ts.map +1 -0
  367. package/dist/unsafe.js +177 -0
  368. package/dist/unsafe.js.map +1 -0
  369. package/dist/validation/config-refusal.d.ts +16 -0
  370. package/dist/validation/config-refusal.d.ts.map +1 -0
  371. package/dist/validation/config-refusal.js +2 -0
  372. package/dist/validation/config-refusal.js.map +1 -0
  373. package/dist/validation/database-config.d.ts +19 -0
  374. package/dist/validation/database-config.d.ts.map +1 -0
  375. package/dist/validation/database-config.js +237 -0
  376. package/dist/validation/database-config.js.map +1 -0
  377. package/dist/validation/default-value.d.ts +21 -0
  378. package/dist/validation/default-value.d.ts.map +1 -0
  379. package/dist/validation/default-value.js +72 -0
  380. package/dist/validation/default-value.js.map +1 -0
  381. package/dist/validation/extension-packs.d.ts +11 -0
  382. package/dist/validation/extension-packs.d.ts.map +1 -0
  383. package/dist/validation/extension-packs.js +53 -0
  384. package/dist/validation/extension-packs.js.map +1 -0
  385. package/dist/validation/field-config.d.ts +35 -21
  386. package/dist/validation/field-config.d.ts.map +1 -1
  387. package/dist/validation/field-config.js +51 -41
  388. package/dist/validation/field-config.js.map +1 -1
  389. package/dist/validation/field-names.d.ts +15 -0
  390. package/dist/validation/field-names.d.ts.map +1 -0
  391. package/dist/validation/field-names.js +155 -0
  392. package/dist/validation/field-names.js.map +1 -0
  393. package/dist/validation/identifier-names.d.ts +4 -0
  394. package/dist/validation/identifier-names.d.ts.map +1 -0
  395. package/dist/validation/identifier-names.js +39 -0
  396. package/dist/validation/identifier-names.js.map +1 -0
  397. package/dist/validation/needs-closure.d.ts +20 -30
  398. package/dist/validation/needs-closure.d.ts.map +1 -1
  399. package/dist/validation/needs-closure.js +29 -105
  400. package/dist/validation/needs-closure.js.map +1 -1
  401. package/dist/validation/relations.d.ts +17 -0
  402. package/dist/validation/relations.d.ts.map +1 -0
  403. package/dist/validation/relations.js +268 -0
  404. package/dist/validation/relations.js.map +1 -0
  405. package/dist/validation/schema.d.ts.map +1 -1
  406. package/dist/validation/schema.js +1 -3
  407. package/dist/validation/schema.js.map +1 -1
  408. package/dist/where/like.d.ts +32 -0
  409. package/dist/where/like.d.ts.map +1 -0
  410. package/dist/where/like.js +42 -0
  411. package/dist/where/like.js.map +1 -0
  412. package/package.json +70 -8
  413. package/.turbo/turbo-build.log +0 -4
  414. package/CLAUDE.md +0 -609
  415. package/dist/access/access-filter.d.ts +0 -241
  416. package/dist/access/access-filter.d.ts.map +0 -1
  417. package/dist/access/access-filter.js +0 -692
  418. package/dist/access/access-filter.js.map +0 -1
  419. package/dist/access/access-filter.test.d.ts +0 -2
  420. package/dist/access/access-filter.test.d.ts.map +0 -1
  421. package/dist/access/access-filter.test.js +0 -1256
  422. package/dist/access/access-filter.test.js.map +0 -1
  423. package/dist/access/declared-dependencies.test.d.ts +0 -2
  424. package/dist/access/declared-dependencies.test.d.ts.map +0 -1
  425. package/dist/access/declared-dependencies.test.js +0 -226
  426. package/dist/access/declared-dependencies.test.js.map +0 -1
  427. package/dist/access/denied-relation-visibility.test.d.ts +0 -2
  428. package/dist/access/denied-relation-visibility.test.d.ts.map +0 -1
  429. package/dist/access/denied-relation-visibility.test.js +0 -114
  430. package/dist/access/denied-relation-visibility.test.js.map +0 -1
  431. package/dist/access/engine.test.d.ts +0 -2
  432. package/dist/access/engine.test.d.ts.map +0 -1
  433. package/dist/access/engine.test.js +0 -56
  434. package/dist/access/engine.test.js.map +0 -1
  435. package/dist/access/field-access.test.d.ts +0 -2
  436. package/dist/access/field-access.test.d.ts.map +0 -1
  437. package/dist/access/field-access.test.js +0 -635
  438. package/dist/access/field-access.test.js.map +0 -1
  439. package/dist/access/multi-column-read-write.test.d.ts +0 -2
  440. package/dist/access/multi-column-read-write.test.d.ts.map +0 -1
  441. package/dist/access/multi-column-read-write.test.js +0 -183
  442. package/dist/access/multi-column-read-write.test.js.map +0 -1
  443. package/dist/access/relationship-count.d.ts +0 -98
  444. package/dist/access/relationship-count.d.ts.map +0 -1
  445. package/dist/access/relationship-count.js +0 -262
  446. package/dist/access/relationship-count.js.map +0 -1
  447. package/dist/access/relationship-count.test.d.ts +0 -2
  448. package/dist/access/relationship-count.test.d.ts.map +0 -1
  449. package/dist/access/relationship-count.test.js +0 -247
  450. package/dist/access/relationship-count.test.js.map +0 -1
  451. package/dist/access/relationship-label-filter.d.ts +0 -45
  452. package/dist/access/relationship-label-filter.d.ts.map +0 -1
  453. package/dist/access/relationship-label-filter.js +0 -22
  454. package/dist/access/relationship-label-filter.js.map +0 -1
  455. package/dist/access/relationship-label-filter.test.d.ts +0 -2
  456. package/dist/access/relationship-label-filter.test.d.ts.map +0 -1
  457. package/dist/access/relationship-label-filter.test.js +0 -89
  458. package/dist/access/relationship-label-filter.test.js.map +0 -1
  459. package/dist/access/synthetic-include-read.test.d.ts +0 -2
  460. package/dist/access/synthetic-include-read.test.d.ts.map +0 -1
  461. package/dist/access/synthetic-include-read.test.js +0 -121
  462. package/dist/access/synthetic-include-read.test.js.map +0 -1
  463. package/dist/context/nested-operations.d.ts +0 -74
  464. package/dist/context/nested-operations.d.ts.map +0 -1
  465. package/dist/context/nested-operations.js +0 -847
  466. package/dist/context/nested-operations.js.map +0 -1
  467. package/dist/fields/calendar-day.test.d.ts +0 -2
  468. package/dist/fields/calendar-day.test.d.ts.map +0 -1
  469. package/dist/fields/calendar-day.test.js +0 -246
  470. package/dist/fields/calendar-day.test.js.map +0 -1
  471. package/dist/fields/format-prisma-default.d.ts +0 -35
  472. package/dist/fields/format-prisma-default.d.ts.map +0 -1
  473. package/dist/fields/format-prisma-default.js +0 -49
  474. package/dist/fields/format-prisma-default.js.map +0 -1
  475. package/dist/fields/format-prisma-default.test.d.ts +0 -2
  476. package/dist/fields/format-prisma-default.test.d.ts.map +0 -1
  477. package/dist/fields/format-prisma-default.test.js +0 -54
  478. package/dist/fields/format-prisma-default.test.js.map +0 -1
  479. package/dist/fields/relationship-foreign-key.test.d.ts +0 -2
  480. package/dist/fields/relationship-foreign-key.test.d.ts.map +0 -1
  481. package/dist/fields/relationship-foreign-key.test.js +0 -18
  482. package/dist/fields/relationship-foreign-key.test.js.map +0 -1
  483. package/dist/fields/select.test.d.ts +0 -2
  484. package/dist/fields/select.test.d.ts.map +0 -1
  485. package/dist/fields/select.test.js +0 -279
  486. package/dist/fields/select.test.js.map +0 -1
  487. package/dist/fields/text-keystone-compat.test.d.ts +0 -2
  488. package/dist/fields/text-keystone-compat.test.d.ts.map +0 -1
  489. package/dist/fields/text-keystone-compat.test.js +0 -93
  490. package/dist/fields/text-keystone-compat.test.js.map +0 -1
  491. package/dist/filter/filter.test.d.ts +0 -2
  492. package/dist/filter/filter.test.d.ts.map +0 -1
  493. package/dist/filter/filter.test.js +0 -431
  494. package/dist/filter/filter.test.js.map +0 -1
  495. package/dist/filter/serialize.test.d.ts +0 -2
  496. package/dist/filter/serialize.test.d.ts.map +0 -1
  497. package/dist/filter/serialize.test.js +0 -83
  498. package/dist/filter/serialize.test.js.map +0 -1
  499. package/dist/index.test.d.ts +0 -2
  500. package/dist/index.test.d.ts.map +0 -1
  501. package/dist/index.test.js +0 -33
  502. package/dist/index.test.js.map +0 -1
  503. package/dist/lib/case-utils.test.d.ts +0 -2
  504. package/dist/lib/case-utils.test.d.ts.map +0 -1
  505. package/dist/lib/case-utils.test.js +0 -123
  506. package/dist/lib/case-utils.test.js.map +0 -1
  507. package/dist/query/index.d.ts +0 -127
  508. package/dist/query/index.d.ts.map +0 -1
  509. package/dist/query/index.js +0 -179
  510. package/dist/query/index.js.map +0 -1
  511. package/dist/query/index.test.d.ts +0 -2
  512. package/dist/query/index.test.d.ts.map +0 -1
  513. package/dist/query/index.test.js +0 -632
  514. package/dist/query/index.test.js.map +0 -1
  515. package/dist/query/relationship-options.test.d.ts +0 -2
  516. package/dist/query/relationship-options.test.d.ts.map +0 -1
  517. package/dist/query/relationship-options.test.js +0 -150
  518. package/dist/query/relationship-options.test.js.map +0 -1
  519. package/dist/validation/field-config.test.d.ts +0 -2
  520. package/dist/validation/field-config.test.d.ts.map +0 -1
  521. package/dist/validation/field-config.test.js +0 -159
  522. package/dist/validation/field-config.test.js.map +0 -1
  523. package/dist/validation/schema.test.d.ts +0 -2
  524. package/dist/validation/schema.test.d.ts.map +0 -1
  525. package/dist/validation/schema.test.js +0 -409
  526. package/dist/validation/schema.test.js.map +0 -1
  527. package/docs/type-distribution-fix.md +0 -136
  528. package/src/access/access-filter.test.ts +0 -1919
  529. package/src/access/access-filter.ts +0 -1041
  530. package/src/access/declared-dependencies.test.ts +0 -277
  531. package/src/access/declared-dependencies.ts +0 -220
  532. package/src/access/denied-relation-visibility.test.ts +0 -173
  533. package/src/access/depth-limits.ts +0 -27
  534. package/src/access/engine.test.ts +0 -67
  535. package/src/access/engine.ts +0 -193
  536. package/src/access/errors.ts +0 -242
  537. package/src/access/field-access.test.ts +0 -792
  538. package/src/access/field-access.ts +0 -353
  539. package/src/access/field-transforms.ts +0 -68
  540. package/src/access/field-visibility.ts +0 -569
  541. package/src/access/index.ts +0 -82
  542. package/src/access/multi-column-read-write.test.ts +0 -305
  543. package/src/access/query-validation.ts +0 -486
  544. package/src/access/relationship-count.test.ts +0 -344
  545. package/src/access/relationship-count.ts +0 -346
  546. package/src/access/relationship-label-filter.test.ts +0 -128
  547. package/src/access/relationship-label-filter.ts +0 -63
  548. package/src/access/synthetic-include-read.test.ts +0 -179
  549. package/src/access/transaction-registry.ts +0 -58
  550. package/src/access/types.ts +0 -391
  551. package/src/config/index.ts +0 -177
  552. package/src/config/label.ts +0 -51
  553. package/src/config/nav-count.ts +0 -77
  554. package/src/config/plugin-engine.ts +0 -261
  555. package/src/config/types.ts +0 -3270
  556. package/src/context/apply-defaults.ts +0 -47
  557. package/src/context/hook-pipeline.ts +0 -137
  558. package/src/context/index.ts +0 -1737
  559. package/src/context/nested-operations.ts +0 -1470
  560. package/src/context/transaction-boundary.ts +0 -485
  561. package/src/context/write-pipeline.ts +0 -732
  562. package/src/extend.ts +0 -28
  563. package/src/fields/calendar-day.test.ts +0 -291
  564. package/src/fields/format-prisma-default.test.ts +0 -64
  565. package/src/fields/format-prisma-default.ts +0 -64
  566. package/src/fields/index.ts +0 -1901
  567. package/src/fields/relationship-foreign-key.test.ts +0 -29
  568. package/src/fields/select.test.ts +0 -336
  569. package/src/fields/text-keystone-compat.test.ts +0 -126
  570. package/src/filter/collect.ts +0 -108
  571. package/src/filter/filter.test.ts +0 -538
  572. package/src/filter/index.ts +0 -26
  573. package/src/filter/map.ts +0 -63
  574. package/src/filter/parse.ts +0 -99
  575. package/src/filter/serialize.test.ts +0 -115
  576. package/src/filter/serialize.ts +0 -73
  577. package/src/filter/types.ts +0 -120
  578. package/src/hooks/index.ts +0 -752
  579. package/src/index.test.ts +0 -50
  580. package/src/index.ts +0 -192
  581. package/src/internal.ts +0 -61
  582. package/src/lib/case-utils.test.ts +0 -159
  583. package/src/lib/case-utils.ts +0 -68
  584. package/src/lib/prisma-errors.ts +0 -86
  585. package/src/mcp/constants.ts +0 -24
  586. package/src/mcp/field-schema.ts +0 -84
  587. package/src/mcp/handler.ts +0 -633
  588. package/src/mcp/index.ts +0 -7
  589. package/src/mcp/projection.ts +0 -497
  590. package/src/mcp/types.ts +0 -18
  591. package/src/query/index.test.ts +0 -830
  592. package/src/query/index.ts +0 -352
  593. package/src/query/relationship-options.test.ts +0 -194
  594. package/src/query/relationship-options.ts +0 -78
  595. package/src/utils/password.ts +0 -80
  596. package/src/validation/field-config.test.ts +0 -199
  597. package/src/validation/field-config.ts +0 -139
  598. package/src/validation/needs-closure.ts +0 -188
  599. package/src/validation/schema.test.ts +0 -487
  600. package/src/validation/schema.ts +0 -51
  601. package/tests/access-relationships.test.ts +0 -646
  602. package/tests/access.test.ts +0 -590
  603. package/tests/apply-defaults.test.ts +0 -119
  604. package/tests/bare-read-scalars.test.ts +0 -147
  605. package/tests/computed-field-selective-evaluation.test.ts +0 -418
  606. package/tests/config.test.ts +0 -242
  607. package/tests/context.test.ts +0 -3146
  608. package/tests/default-value-create.test.ts +0 -299
  609. package/tests/field-hooks.test.ts +0 -410
  610. package/tests/field-types.test.ts +0 -1291
  611. package/tests/hook-context-secured.test.ts +0 -424
  612. package/tests/hook-pipeline.test.ts +0 -233
  613. package/tests/hooks.test.ts +0 -481
  614. package/tests/interactive-transaction.test.ts +0 -444
  615. package/tests/label.test.ts +0 -135
  616. package/tests/mcp-fields-projection-access.test.ts +0 -250
  617. package/tests/mcp-handler.test.ts +0 -1411
  618. package/tests/multi-column-validation-ordering.test.ts +0 -305
  619. package/tests/nav-count.test.ts +0 -189
  620. package/tests/needs-declared-dependencies.test.ts +0 -503
  621. package/tests/nested-access-and-hooks.test.ts +0 -2566
  622. package/tests/nested-operation-registry.test.ts +0 -317
  623. package/tests/nested-write-hooks.test.ts +0 -864
  624. package/tests/nested-write-synthetic-relation.test.ts +0 -437
  625. package/tests/password-type-distribution.test.ts +0 -154
  626. package/tests/password-types.test.ts +0 -174
  627. package/tests/password.test.ts +0 -263
  628. package/tests/plugin-engine.test.ts +0 -1155
  629. package/tests/prisma-errors.test.ts +0 -141
  630. package/tests/resolve-chain.test.ts +0 -411
  631. package/tests/singleton.test.ts +0 -421
  632. package/tests/sudo.test.ts +0 -676
  633. package/tests/to-one-include-access-filter.test.ts +0 -172
  634. package/tests/transaction-boundary-hooks.test.ts +0 -710
  635. package/tests/transaction-boundary-outermost.test.ts +0 -530
  636. package/tests/virtual-fields.test.ts +0 -421
  637. package/tests/with-session.test.ts +0 -243
  638. package/tests/write-pipeline.test.ts +0 -617
  639. package/tsconfig.json +0 -12
  640. package/tsconfig.tsbuildinfo +0 -1
  641. package/vitest.config.ts +0 -69
@@ -1,13 +1,23 @@
1
- import { checkAccess, mergeFilters, filterReadableFields, buildAccessScopedInclude, buildAccessScopedWhere, stripVirtualFieldsFromInclude, foldDeclaredDependencies, validateQueryKeys, validateQueryFieldReadAccess, resolveToOneAccessVisibility, emptyToOneAccessFilterTree, emptyCountAccessDenialTree, } from '../access/index.js';
1
+ import { checkAccess } from '../access/index.js';
2
+ import { resolveSyntheticReverseRelation } from '../access/engine.js';
2
3
  import { ValidationError, DatabaseError } from '../hooks/index.js';
3
- import { getDbKey } from '../lib/case-utils.js';
4
- import { uniqueConstraintOf } from '../lib/prisma-errors.js';
5
- import { buildInclude, pickFields, isFragment, buildFieldSelectionScope } from '../query/index.js';
6
- import { getRelationshipOptions } from '../query/relationship-options.js';
4
+ import { databaseErrorMessage, normalizeDatabaseError } from '../lib/prisma-errors.js';
5
+ import { isClientSafeError } from '../lib/client-safe-error.js';
6
+ import { nullPrototypeRegistry } from '../lib/null-prototype-registry.js';
7
+ import { warnOnce } from '../lib/warn-once.js';
8
+ import { createSecuredRead } from '../secured/read.js';
9
+ import { createLivenessProbe, createRowLockLane, RowLockUnavailableError, unusableRowLockLane, } from '../secured/lock.js';
10
+ import { createUnsafeSurface, createUnsafeTransactionSurface, unavailableUnsafeSurface, } from '../unsafe.js';
11
+ import { ENGINE_FACE, engineContextOf } from './engine-context.js';
12
+ import { withOrigin } from '../origin.js';
13
+ import { getRelationshipOptions, isRelationshipLabelReadable, } from '../query/relationship-options.js';
7
14
  import { runWritePipeline, createWriteStrategy, updateWriteStrategy, deleteWriteStrategy, } from './write-pipeline.js';
8
- import { AfterTransactionError } from './transaction-boundary.js';
9
- import { TransactionRegistry } from '../access/transaction-registry.js';
10
- const selectWarnings = new Set();
15
+ import { resolveJunctionEdge, ownsForeignKey } from './junction.js';
16
+ import { isRelationshipField } from '../fields/index.js';
17
+ import { parseListId } from '../contract/id-boundary.js';
18
+ import { reportAfterTransactionFailures } from './transaction-boundary.js';
19
+ import { TransactionRegistry, TransactionRolledBackError, } from '../access/transaction-registry.js';
20
+ export { TransactionRolledBackError };
11
21
  /**
12
22
  * Warn once per (list, operation) when a caller passes `select` to a read op
13
23
  * that ignores it. See "Narrowing Reads" in packages/core/CLAUDE.md.
@@ -15,13 +25,9 @@ const selectWarnings = new Set();
15
25
  function warnIfSelectIgnored(args, listName, operation) {
16
26
  if (!args || args.select === undefined)
17
27
  return;
18
- const key = `${listName}.${operation}`;
19
- if (selectWarnings.has(key))
20
- return;
21
- selectWarnings.add(key);
22
- console.warn(`[@opensaas/stack-core] \`select\` is ignored by context.db.${getDbKey(listName)}.${operation}() ` +
28
+ warnOnce(`select-ignored:${listName}.${operation}`, `[@opensaas/stack-core] \`select\` is ignored by context.db.${listName}.${operation}() ` +
23
29
  `and the full (access-filtered) record is returned. ` +
24
- `Narrow a read with \`include\` or a fragment \`query\` instead. ` +
30
+ `Narrow a read with \`include\`, or with \`.select()\` on the secured surface, instead. ` +
25
31
  `See https://stack.opensaas.au/docs/concepts/queries`);
26
32
  }
27
33
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
@@ -29,53 +35,59 @@ function isSingletonList(listConfig) {
29
35
  return !!listConfig.isSingleton;
30
36
  }
31
37
  /**
32
- * Compute the set of single-field unique selectors a `findUnique` `where` may be
33
- * keyed by, derived from what the list config exposes at runtime: `id`, plus any
34
- * field declared `isIndexed: 'unique'` — for a `relationship` field, this is the
35
- * foreign-key column name (`<field>Id`), since that's the column Prisma marks
36
- * `@unique`, not the relation field itself.
37
- *
38
- * The config exposes no list-level compound (`@@unique`) declaration, so this
39
- * cannot validate a compound `<Model>_<a>_<b>` selector — `where` must contain
40
- * exactly one recognised single-field unique key and no others. This rejects
41
- * non-unique filters (#567) without ever rejecting a valid single-field unique
42
- * lookup; a compound-unique or otherwise non-unique lookup should use
43
- * `findFirst` instead (see #565).
38
+ * Whether `fieldName` on `listKey` owns a foreign-key column — the property
39
+ * `removeRelated`/`createRelated`/`linkRelated` actually need, rather than
40
+ * `many`, which is only a proxy for it: a non-owning to-one (the inverse half
41
+ * of a one-to-one) has `many` falsy exactly like an owning one, and a
42
+ * synthetic `from_<List>_<field>` back-relation is never declared, so it is
43
+ * never itself in `listConfig.fields` (#1442).
44
44
  */
45
+ function classifyBackReference(listKey, fieldName,
45
46
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
46
- function getUniqueWhereKeys(listConfig) {
47
- const keys = new Set(['id']);
48
- for (const [fieldKey, fieldConfig] of Object.entries(listConfig.fields)) {
49
- if (!fieldConfig || typeof fieldConfig !== 'object')
50
- continue;
51
- if (!('isIndexed' in fieldConfig) || fieldConfig.isIndexed !== 'unique')
52
- continue;
53
- if (fieldConfig.type === 'relationship') {
54
- // A unique relationship's `@unique` lives on the FK column `<field>Id`.
55
- keys.add(`${fieldKey}Id`);
56
- }
57
- else {
58
- keys.add(fieldKey);
59
- }
47
+ listConfig, config) {
48
+ const field = listConfig.fields[fieldName];
49
+ if (isRelationshipField(field)) {
50
+ return ownsForeignKey(config, listKey, fieldName, field)
51
+ ? { kind: 'owning', field }
52
+ : { kind: 'nonOwning' };
60
53
  }
61
- return keys;
54
+ return resolveSyntheticReverseRelation(fieldName, listKey, config) !== null
55
+ ? { kind: 'nonOwning' }
56
+ : { kind: 'notRelationship' };
57
+ }
58
+ function isRawRowCollection(value) {
59
+ return (typeof value === 'object' &&
60
+ value !== null &&
61
+ typeof value.where === 'function' &&
62
+ typeof value.select === 'function' &&
63
+ typeof value.first === 'function');
62
64
  }
63
65
  /**
64
- * Enforce Keystone `findOne` semantics for `findUnique`: the caller-supplied
65
- * `where` must be a valid unique selector. A non-unique `where` is a caller-shape
66
- * error (not an access denial), so this THROWS rather than silently returning
67
- * `null` — consistent with the fail-loud-on-misuse stance of PRD #581. A
68
- * non-unique single-row lookup should use `findFirst` instead (see #565).
66
+ * `update` and `delete` target a row by its identity: the engine lowers `id`
67
+ * alone into the write's predicate, so a `where` naming anything else — a
68
+ * secondary unique column included — selects nothing. That is a caller-shape
69
+ * error, not an access denial, so it THROWS rather than returning the
70
+ * denied-or-gone `null`.
71
+ *
72
+ * `ListIdentityWhere` makes it a compile error for a typed caller; this is the
73
+ * runtime half, for a payload that reached the engine untyped.
69
74
  */
70
- function assertUniqueWhere(where, uniqueKeys, listName) {
75
+ function assertIdentityWhere(where, listName, terminal) {
71
76
  const keys = where ? Object.keys(where) : [];
72
- const message = `findUnique on "${listName}" requires a unique \`where\` (a single unique key such as ` +
73
- `${Array.from(uniqueKeys).join(', ')}). ` +
74
- `Received: ${keys.length === 0 ? '{}' : `{ ${keys.join(', ')} }`}. ` +
75
- `Use \`findFirst\` for a non-unique single-row lookup.`;
76
- if (keys.length !== 1 || !uniqueKeys.has(keys[0])) {
77
- throw new ValidationError([message], {});
77
+ const id = where?.id;
78
+ if (keys.length === 1 && keys[0] === 'id' && (typeof id === 'string' || typeof id === 'number')) {
79
+ return;
78
80
  }
81
+ const received = keys.length === 0
82
+ ? '{}'
83
+ : keys.length === 1 && keys[0] === 'id'
84
+ ? `{ id: ${id === null ? 'null' : typeof id} }`
85
+ : `{ ${keys.join(', ')} }`;
86
+ throw new ValidationError([
87
+ `${terminal} on "${listName}" requires \`where: { id }\` — a row is written by its ` +
88
+ `identity, and no other column selects one. Received: ${received}. Find the row first ` +
89
+ `(\`where(…).first()\`) and write it by its \`id\`.`,
90
+ ], {});
79
91
  }
80
92
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
81
93
  function shouldAutoCreate(listConfig) {
@@ -85,89 +97,353 @@ function shouldAutoCreate(listConfig) {
85
97
  return true;
86
98
  return listConfig.isSingleton.autoCreate !== false;
87
99
  }
88
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
89
- function getDefaultData(listConfig) {
90
- const data = {};
91
- for (const [fieldKey, fieldConfig] of Object.entries(listConfig.fields)) {
92
- if (fieldConfig.virtual)
93
- continue;
94
- if (fieldKey === 'id' || fieldKey === 'createdAt' || fieldKey === 'updatedAt')
95
- continue;
96
- if ('defaultValue' in fieldConfig && fieldConfig.defaultValue !== undefined) {
97
- data[fieldKey] = fieldConfig.defaultValue;
98
- }
100
+ /**
101
+ * Thrown when `context.transaction()` can neither open a transaction nor join
102
+ * one.
103
+ *
104
+ * The call's whole contract is that its callback's writes commit or roll back
105
+ * together, so running the callback anyway would hand back that guarantee
106
+ * without holding it. A context reaches this only when it was assembled
107
+ * without the Prisma 8 client the opener is derived from — a hand-built ORM
108
+ * double, or `getContext` called without its `client` argument.
109
+ */
110
+ export class TransactionUnavailableError extends Error {
111
+ constructor() {
112
+ super(`context.transaction() has no client to open a transaction on and no enclosing ` +
113
+ `transaction to join, so its callback's writes would commit one by one with no ` +
114
+ `rollback between them. Build the context over the Prisma 8 client — \`getContext\`'s ` +
115
+ `\`client\` argument, which the generated context passes — rather than over an ORM ` +
116
+ `handle alone.`);
117
+ this.name = 'TransactionUnavailableError';
118
+ }
119
+ }
120
+ /**
121
+ * Thrown when the transaction's own collections cannot be resolved for every
122
+ * list the config declares, after the client's could be.
123
+ *
124
+ * The two roots have the same shape, so this is an ORM surprise rather than a
125
+ * wiring fault — and the alternative to reporting it is binding `db` to a
126
+ * half-built handle whose writes land outside the open transaction.
127
+ */
128
+ export class TransactionOrmHandleError extends Error {
129
+ constructor() {
130
+ super(`The stack opened a transaction whose ORM collections could not be resolved, though the ` +
131
+ `client's could. The engine's handle must be bound to the transaction or its writes ` +
132
+ `would commit outside it, so the transaction is rolled back rather than run unbound.`);
133
+ this.name = 'TransactionOrmHandleError';
99
134
  }
100
- return data;
101
135
  }
102
- // A camelCase field name (e.g. a relationship's `tenantId` foreign key) needs
103
- // its word boundary split before title-casing, or it reads as one run-together
104
- // word ("Tenantid") in a user-facing unique-constraint message.
105
- function humanizeFieldName(fieldName) {
106
- const spaced = fieldName.replace(/([a-z0-9])([A-Z])/g, '$1 $2');
107
- return spaced.charAt(0).toUpperCase() + spaced.slice(1);
136
+ const DEFAULT_NAMESPACE = 'public';
137
+ function reachable(container, key) {
138
+ if (container === null || (typeof container !== 'object' && typeof container !== 'function')) {
139
+ return undefined;
140
+ }
141
+ return Reflect.get(container, key);
108
142
  }
109
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
110
- function parsePrismaError(error, listConfig) {
111
- if (error &&
112
- typeof error === 'object' &&
113
- 'code' in error &&
114
- 'meta' in error &&
115
- typeof error.code === 'string') {
116
- const prismaError = error;
117
- // P2002 is Prisma's unique constraint violation code.
118
- if (prismaError.code === 'P2002') {
119
- const target = uniqueConstraintOf(prismaError)?.fields;
120
- const fieldErrors = {};
121
- if (target && target.length > 0) {
122
- for (const fieldName of target) {
123
- const fieldConfig = listConfig.fields[fieldName];
124
- if (fieldConfig) {
125
- fieldErrors[fieldName] =
126
- `This ${humanizeFieldName(fieldName).toLowerCase()} is already in use`;
127
- }
128
- else {
129
- fieldErrors[fieldName] = `This value is already in use`;
130
- }
131
- }
132
- const fieldLabels = target.map(humanizeFieldName).join(', ');
133
- return new DatabaseError(`${fieldLabels} must be unique. The value you entered is already in use.`, fieldErrors, prismaError.code);
134
- }
135
- return new DatabaseError('A record with this value already exists', {}, prismaError.code);
143
+ /**
144
+ * The config's own list-to-namespace shape, independent of any `orm` root. A
145
+ * config's lists don't change during a context's life, so a caller that will
146
+ * resolve the same config against more than one root (the client's own, then
147
+ * each transaction's) derives this once and reuses it, rather than re-walking
148
+ * `config.lists` on every resolution.
149
+ */
150
+ function ormListShapeFor(config) {
151
+ return Object.entries(config.lists).map(([listKey, listConfig]) => ({
152
+ listKey,
153
+ namespaceName: listConfig.db?.schema ?? DEFAULT_NAMESPACE,
154
+ }));
155
+ }
156
+ /**
157
+ * The engine's ORM handle, resolved off a Prisma 8 `orm` root against an
158
+ * already-derived {@link OrmListShape}.
159
+ *
160
+ * A Prisma 8 client exposes its collections at `orm.<namespace>.<Model>` while
161
+ * the engine reaches a model by db key, so a handle bound to a transaction has
162
+ * to be rebuilt rather than reused — the same reconciliation the test harness
163
+ * performs, over the config's lists rather than the derived contract's models
164
+ * (both spell the model name as the list key and the namespace as `db.schema`).
165
+ *
166
+ * Reports the first list it cannot reach rather than a bare failure, so a
167
+ * caller can name the collection that is missing instead of every list the
168
+ * config declares.
169
+ *
170
+ * Reads go through `Reflect.get`: `orm` and its namespaces are Proxies with a
171
+ * `get` trap and no `has` trap, so `key in namespace` reports false for a
172
+ * collection that is right there.
173
+ */
174
+ function resolveOrmHandle(shape, orm) {
175
+ const models = {};
176
+ for (const { listKey, namespaceName } of shape) {
177
+ const namespace = reachable(orm, namespaceName);
178
+ const collection = reachable(namespace, listKey);
179
+ if (collection === null ||
180
+ (typeof collection !== 'object' && typeof collection !== 'function')) {
181
+ return { unresolved: { list: listKey, namespace: namespaceName } };
136
182
  }
137
- return new DatabaseError(prismaError.message || 'A database error occurred', {}, prismaError.code);
183
+ models[listKey] = collection;
138
184
  }
139
- if (error instanceof Error) {
140
- return error;
185
+ return { handle: models };
186
+ }
187
+ function ormHandleFor(config, orm) {
188
+ return resolveOrmHandle(ormListShapeFor(config), orm);
189
+ }
190
+ /**
191
+ * Thrown when a client's collections cannot be resolved for every list the
192
+ * config declares. The engine reaches every model through the handle, so a
193
+ * context built over a partial one refuses each unresolved list's operations
194
+ * with `OrmModelMissingError` at its own call site instead of here.
195
+ */
196
+ export class OrmHandleUnresolvableError extends Error {
197
+ list;
198
+ namespace;
199
+ constructor(list, namespace) {
200
+ super(`The ORM client exposes no collection "${list}" in namespace "${namespace}", which this ` +
201
+ `config declares as a list. Re-run \`opensaas generate\` so the emitted contract matches ` +
202
+ `the config.`);
203
+ this.list = list;
204
+ this.namespace = namespace;
205
+ this.name = 'OrmHandleUnresolvableError';
206
+ }
207
+ }
208
+ /**
209
+ * The engine's ORM handle for a Prisma 8 client's `orm` root — what
210
+ * {@link getContext} takes as its `ormHandle`. A caller that has a client
211
+ * rather than a handle resolves it here, so the generated context, the test
212
+ * harness and `context.transaction()` all hand the engine the same shape.
213
+ *
214
+ * The returned handle carries no transaction capability and no Unsafe
215
+ * surface of its own — both come only from the client itself, which a caller
216
+ * passes separately as `getContext`'s own `client` argument. Handing
217
+ * `getContext` this handle alone (`getContext(config, requireOrmHandle(config, db.orm), session)`)
218
+ * builds a context whose writes run with no rollback guarantee; see the
219
+ * `client` parameter's own docblock.
220
+ *
221
+ * @throws {OrmHandleUnresolvableError} when any declared list is unreachable.
222
+ */
223
+ export function requireOrmHandle(config, orm) {
224
+ const { handle, unresolved } = ormHandleFor(config, orm);
225
+ if (handle === undefined) {
226
+ throw new OrmHandleUnresolvableError(unresolved.list, unresolved.namespace);
227
+ }
228
+ return handle;
229
+ }
230
+ /**
231
+ * The transaction opener for a context over `client`, or `undefined` when this
232
+ * context cannot open one: no Prisma 8 client, or a context already bound to an
233
+ * enclosing transaction (`unsafeTransaction`). A write reached through a
234
+ * context with no opener runs directly against the handle it was given, joining
235
+ * whatever transaction is already open around it (ADR-0028).
236
+ *
237
+ * A client whose collections do not cover the config throws here rather than
238
+ * yielding no opener: an unresolvable handle downgrades every write to
239
+ * non-transactional, which is the loss of the rollback guarantee this opener
240
+ * exists to provide.
241
+ *
242
+ * The list-to-namespace shape is derived from `config` exactly ONCE, here —
243
+ * this function itself runs once per context construction — and the returned
244
+ * closure reuses it for every write's own transaction, rather than re-walking
245
+ * `config.lists` inside `client.transaction()` on each call. Only the `orm`
246
+ * root differs per write (`tx.orm` is a distinct object per transaction, so
247
+ * the resolved handle itself cannot be shared); the shape it is resolved
248
+ * against cannot change during the context's life (issue #1266).
249
+ */
250
+ function transactionOpenerFor(config, client, unsafeTransaction) {
251
+ if (client === undefined || unsafeTransaction !== undefined)
252
+ return undefined;
253
+ const shape = ormListShapeFor(config);
254
+ const { unresolved } = resolveOrmHandle(shape, client.orm);
255
+ if (unresolved !== undefined) {
256
+ throw new OrmHandleUnresolvableError(unresolved.list, unresolved.namespace);
141
257
  }
142
- return new Error('An unknown error occurred');
258
+ return (run) => client.transaction(async (tx) => {
259
+ const { handle } = resolveOrmHandle(shape, tx.orm);
260
+ if (handle === undefined)
261
+ throw new TransactionOrmHandleError();
262
+ return await run({ ormHandle: handle, unsafe: tx, rowLock: rowLockSeat(client, tx) });
263
+ });
264
+ }
265
+ function watchUnsafeReach(surface, owner) {
266
+ if (owner === undefined)
267
+ return surface;
268
+ return new Proxy(surface, {
269
+ get(target, key) {
270
+ owner.noteUnsafeReached();
271
+ return Reflect.get(target, key);
272
+ },
273
+ });
274
+ }
275
+ function throwIfPoisoned(registry) {
276
+ if (registry.isPoisoned)
277
+ throw new TransactionRolledBackError({ cause: registry.poisonCause });
143
278
  }
144
279
  /**
145
280
  * Drain a `context.transaction()` owner's deferral registry once its callback
146
281
  * (and any real underlying transaction) has settled (ADR-0028). A transaction/
147
- * callback error always wins — compensators still all run, but their errors
148
- * are discarded in favor of re-surfacing the original, matching the Write
149
- * Pipeline's `txError` precedence — otherwise any deferred `afterTransaction`
150
- * errors reject with {@link AfterTransactionError} even though the callback
151
- * succeeded and the transaction committed.
282
+ * callback error always wins and is re-surfaced; deferred `afterTransaction`
283
+ * errors never reject — they go to `onAfterTransactionError` (ADR-0074).
284
+ *
285
+ * The settle is the second normalisation site (ADR-0042). PostgreSQL raises
286
+ * some failures at `COMMIT`, after every terminal in the callback has already
287
+ * returned — a `23505` on a `DEFERRABLE INITIALLY DEFERRED` constraint, by
288
+ * design — so the error the owner observes is normalised here, BEFORE the
289
+ * deferred-hook flush, which keeps ADR-0028's precedence rule operating on a
290
+ * normalised value.
152
291
  */
153
- async function settleTransactionOwner(settled, registry) {
292
+ async function settleTransactionOwner(settled, registry, config) {
154
293
  const errors = [];
155
294
  let result;
156
295
  try {
157
296
  result = await settled;
158
297
  }
159
- catch (err) {
298
+ catch (raised) {
299
+ const err = normalizeDatabaseError(raised, config);
160
300
  const outcome = { status: 'rolled-back', error: err };
161
- await registry.drain(outcome, errors);
301
+ try {
302
+ await registry.drain(outcome, errors);
303
+ }
304
+ finally {
305
+ await reportAfterTransactionFailures(config, errors);
306
+ }
162
307
  throw err;
163
308
  }
164
- await registry.drain({ status: 'committed' }, errors);
165
- if (errors.length > 0) {
166
- throw new AfterTransactionError(errors);
309
+ try {
310
+ await registry.drain({ status: 'committed' }, errors);
311
+ }
312
+ finally {
313
+ await reportAfterTransactionFailures(config, errors);
167
314
  }
168
315
  return result;
169
316
  }
170
- export function getContext(config, prisma, session, storage, _isSudo = false,
317
+ async function joinNested(fn, face, owner) {
318
+ try {
319
+ return await fn(face);
320
+ }
321
+ catch (err) {
322
+ owner.poison(err);
323
+ throw err;
324
+ }
325
+ }
326
+ /**
327
+ * The transaction-bound face of a context: everything it already carries, plus
328
+ * `advisoryLock`, and with `sudo()`, `withSession()` and `transaction()`
329
+ * answering in the same face rather than dropping back to the plain one
330
+ * (ADR-0047).
331
+ *
332
+ * A wrapper rather than a second `getContext` branch, because the difference
333
+ * between the two shapes is exactly these four members — `db` is the same
334
+ * object, already built over the transaction's own collections and its lock
335
+ * lane. The nested `transaction()` joins the owner's transaction and poisons it
336
+ * if the callback rejects (ADR-0012); it is spelled here so the callback is
337
+ * handed this face.
338
+ */
339
+ function transactionFace(base, lock, owner) {
340
+ const face = {
341
+ ...base,
342
+ advisoryLock: async (key) => {
343
+ if (lock === undefined)
344
+ throw new RowLockUnavailableError('advisoryLock()');
345
+ await lock.advisory(key);
346
+ },
347
+ sudo: () => transactionFace(base.sudo(), lock, owner),
348
+ withSession: (session) => transactionFace(base.withSession(session), lock, owner),
349
+ transaction: (fn) => joinNested(fn, face, owner),
350
+ };
351
+ return face;
352
+ }
353
+ // A database failure reaches the client as the stack's own message (ADR-0042),
354
+ // so the driver's diagnostic text — carried on `cause` — reaches no channel at
355
+ // all unless it is logged here. Deleting this closes the operator's only view
356
+ // of a production database failure.
357
+ function logDatabaseFailure(error, listKey, action) {
358
+ if (!(error instanceof DatabaseError))
359
+ return;
360
+ console.error(`Database error on "${action}" for list "${listKey}":`, error.cause ?? error);
361
+ }
362
+ function clientFailure(error, config, listKey, action, options = {}) {
363
+ const classifier = config.ui?.classifyActionError;
364
+ if (classifier) {
365
+ try {
366
+ const classified = classifier(error);
367
+ if (classified &&
368
+ typeof classified.message === 'string' &&
369
+ typeof classified.code === 'string')
370
+ return { error: classified.message, code: classified.code };
371
+ }
372
+ catch (classifierError) {
373
+ console.error('classifyActionError threw:', classifierError);
374
+ }
375
+ }
376
+ const normalized = databaseErrorMessage(error, config);
377
+ if (!isClientSafeError(normalized)) {
378
+ console.error(`Action "${action}" on list "${listKey}" failed:`, error);
379
+ const label = action.charAt(0).toUpperCase() + action.slice(1);
380
+ return {
381
+ error: options.genericMessage ??
382
+ `${label} on "${options.shownListKey ?? listKey}" failed due to an internal error.`,
383
+ };
384
+ }
385
+ logDatabaseFailure(normalized, listKey, action);
386
+ const fieldErrors = normalized instanceof ValidationError || normalized instanceof DatabaseError
387
+ ? normalized.fieldErrors
388
+ : undefined;
389
+ return { error: normalized.message, fieldErrors };
390
+ }
391
+ /**
392
+ * The lock lane a context carries, present only inside a transaction — which
393
+ * is what makes `forUpdate()` answerable there and a refusal everywhere else.
394
+ * The raw tag comes from the client because Prisma's transaction context
395
+ * carries none, and the executor from the transaction because the lock has to
396
+ * be the transaction's (ADR-0047, ADR-0062).
397
+ *
398
+ * Inside a transaction whose client cannot compose the statement the seat is
399
+ * filled by a refusing lane rather than left empty, so `undefined` keeps
400
+ * meaning exactly one thing: there is no transaction.
401
+ */
402
+ function rowLockSeat(client, transaction) {
403
+ if (client === undefined || transaction === undefined)
404
+ return undefined;
405
+ return createRowLockLane(client.raw, client.contract, transaction) ?? unusableRowLockLane();
406
+ }
407
+ /**
408
+ * Thrown when a session handed to `getContext` — directly, through
409
+ * `withSession`, or through `createTestContext` — holds `undefined` for one
410
+ * of its own keys.
411
+ *
412
+ * `session ?? null` treats any non-null value as signed in, and an object
413
+ * is non-null even when every property on it is `undefined`. A session
414
+ * built from an unguarded optional identifier (`getContext({ userId })`
415
+ * where `userId` may be `undefined`) therefore type-checks against the
416
+ * deliberately open `Session` shape and reaches every access rule looking
417
+ * signed in, rather than anonymous (#1397). The fix is to not construct the
418
+ * key at all: `userId ? { userId } : undefined`, never `{ userId }` over a
419
+ * possibly-undefined value.
420
+ */
421
+ export class InvalidSessionError extends Error {
422
+ keys;
423
+ constructor(keys) {
424
+ const plural = keys.length > 1;
425
+ super(`Session key${plural ? 's' : ''} ${keys.map((key) => `"${key}"`).join(', ')} ` +
426
+ `${plural ? 'are' : 'is'} \`undefined\`. getContext treats any non-null session as ` +
427
+ `signed in, so a key holding \`undefined\` reaches access control looking signed in ` +
428
+ `rather than anonymous. Omit the key instead of setting it to \`undefined\` — build the ` +
429
+ `session as \`userId ? { userId } : undefined\`, not \`{ userId }\` over a value that may ` +
430
+ `be \`undefined\`.`);
431
+ this.keys = keys;
432
+ this.name = 'InvalidSessionError';
433
+ }
434
+ }
435
+ /**
436
+ * @throws {InvalidSessionError} when `session` is non-null and holds
437
+ * `undefined` for one of its own keys.
438
+ */
439
+ function assertValidSession(session) {
440
+ if (session === null)
441
+ return;
442
+ const undefinedKeys = Object.keys(session).filter((key) => session[key] === undefined);
443
+ if (undefinedKeys.length > 0)
444
+ throw new InvalidSessionError(undefinedKeys);
445
+ }
446
+ export function getContext(config, ormHandle, session, storage, _isSudo = false,
171
447
  // Internal: when rebuilding the context against a transaction client, reuse the
172
448
  // already-initialised plugin services rather than re-running plugin runtimes.
173
449
  _sharedPlugins,
@@ -175,16 +451,39 @@ _sharedPlugins,
175
451
  // owner's callback body, carry the deferral registry so writes reached
176
452
  // through this context join it instead of firing afterTransaction eagerly.
177
453
  _transactionOwner,
178
- // Internal (ADR-0023, issue #1176): when rebuilding the context for a
179
- // hook-bound write (or a derived `sudo()`/`withSession()` of one), carry the
180
- // resolve chain forward so a write issued from inside a `resolveOutput` hook
181
- // keeps that hook's cycle-guard chain instead of resetting to empty.
182
- _resolveOutputChain) {
454
+ // The Prisma 8 client the Unsafe surface AND the write transaction opener
455
+ // are both built over. Omitted by a caller that assembles a context from a
456
+ // hand-built ORM double: `context.unsafe` then refuses rather than being
457
+ // typed as absent, and — the costlier omission — every `context.db` write
458
+ // runs with no transaction opener, so it commits directly against the
459
+ // handle with no rollback guarantee: exactly the defect #1205 fixed, left
460
+ // undiagnosed until now (a `console.warn` names it once per list and
461
+ // operation, but nothing stops the write itself). Pass the client whenever
462
+ // the caller can.
463
+ client,
464
+ // Internal: the transaction the Unsafe surface binds its executors to, set
465
+ // when rebuilding the context inside `transaction()` (ADR-0056).
466
+ _unsafeTransaction,
467
+ // Internal (ADR-0028, issue #1348): the base-client context a
468
+ // transaction-boundary hook reached through this one must actually be
469
+ // invoked with. Set when this call builds a context bound to (or joining) a
470
+ // transaction — `context.transaction()`'s own transaction-child — and
471
+ // carried through by `sudo()`/`withSession()` unchanged; omitted for a
472
+ // fresh, non-transactional context, which is its own base.
473
+ _baseContext) {
474
+ assertValidSession(session);
183
475
  // Broad type to allow dynamic model access; populated by populateDbDelegate below.
184
476
  const db = {};
477
+ const openTransaction = transactionOpenerFor(config, client, _unsafeTransaction);
478
+ const lock = rowLockSeat(client, _unsafeTransaction);
479
+ const unsafe = client === undefined
480
+ ? unavailableUnsafeSurface()
481
+ : _unsafeTransaction === undefined
482
+ ? createUnsafeSurface(client)
483
+ : watchUnsafeReach(createUnsafeTransactionSurface(client, _unsafeTransaction), _transactionOwner);
185
484
  const context = {
186
485
  session,
187
- prisma: prisma,
486
+ ormHandle,
188
487
  db: db,
189
488
  storage: storage ?? {
190
489
  uploadFile: async () => {
@@ -202,12 +501,20 @@ _resolveOutputChain) {
202
501
  },
203
502
  // Reuse already-initialised plugin services when rebinding to a transaction
204
503
  // client, otherwise start empty and populate via plugin runtimes below.
205
- plugins: _sharedPlugins ?? {},
504
+ // Null-prototype: keyed by author-supplied plugin names, so a plugin named
505
+ // `__proto__` must not reach the object's actual prototype, and a lookup
506
+ // of a name nobody registered (`constructor`, `toString`, …) must come
507
+ // back `undefined` rather than an inherited function.
508
+ plugins: _sharedPlugins ?? nullPrototypeRegistry(),
206
509
  _isSudo,
207
- _resolveOutputChain: _resolveOutputChain ?? [],
510
+ _resolveOutputChain: [],
208
511
  _transactionOwner,
512
+ _transactionOpener: openTransaction,
513
+ _rowLock: lock,
514
+ _config: config,
515
+ _baseContext,
209
516
  };
210
- populateDbDelegate(db, config, prisma, context);
517
+ populateDbDelegate(db, config, ormHandle, context, lock);
211
518
  // Skipped when reusing shared plugins (transaction rebind) so runtimes — and
212
519
  // any side effects they carry — run exactly once per top-level context.
213
520
  if (!_sharedPlugins) {
@@ -217,7 +524,7 @@ _resolveOutputChain) {
217
524
  try {
218
525
  // Passed as a plain second argument rather than a method on
219
526
  // `context` itself — see the `sudo` param doc on `Plugin['runtime']`.
220
- context.plugins[plugin.name] = plugin.runtime(context, () => sudo());
527
+ context.plugins[plugin.name] = plugin.runtime(context, sudo);
221
528
  }
222
529
  catch (error) {
223
530
  console.error(`Error executing runtime for plugin "${plugin.name}":`, error);
@@ -228,15 +535,23 @@ _resolveOutputChain) {
228
535
  // Returns a result object instead of throwing — required for server actions
229
536
  // to work in Next.js production builds.
230
537
  async function serverAction(props) {
231
- const dbKey = getDbKey(props.listKey);
232
- const listConfig = config.lists[props.listKey];
233
- if (!listConfig) {
538
+ if (!Object.hasOwn(config.lists, props.listKey)) {
234
539
  return {
235
540
  success: false,
236
541
  error: `List "${props.listKey}" not found in configuration`,
237
542
  };
238
543
  }
239
- const model = db[dbKey];
544
+ const listConfig = config.lists[props.listKey];
545
+ const model = db[props.listKey];
546
+ // Every id here arrived as a string on the wire, and the id type is per
547
+ // list (ADR-0048), so each one is parsed through the one boundary coercion
548
+ // before it reaches the ORM. `null` is an id the list's key type cannot
549
+ // hold — refused here rather than sent on as a `NaN` or a Postgres type
550
+ // error.
551
+ const parseId = (listKey, raw) => {
552
+ const parsed = parseListId(config, listKey, raw);
553
+ return parsed.ok ? parsed.value : null;
554
+ };
240
555
  // Bulk delete: remove each id row-by-row through the secured context,
241
556
  // honouring Silent failure — a denied (or missing) row returns `null` and is
242
557
  // simply not counted. Returns "N of M" so partial denials are visible without
@@ -244,7 +559,10 @@ _resolveOutputChain) {
244
559
  // rest.
245
560
  if (props.action === 'bulkDelete') {
246
561
  let deleted = 0;
247
- for (const id of props.ids) {
562
+ for (const raw of props.ids) {
563
+ const id = parseId(props.listKey, raw);
564
+ if (id === null)
565
+ continue;
248
566
  try {
249
567
  const result = await model.delete({ where: { id } });
250
568
  if (result !== null && result !== undefined)
@@ -272,17 +590,17 @@ _resolveOutputChain) {
272
590
  error: `Bulk action "${props.key}" not found on list "${props.listKey}"`,
273
591
  };
274
592
  }
275
- if (action.hasAccess) {
276
- const allowed = await action.hasAccess({
277
- session: context.session,
278
- context,
279
- listKey: props.listKey,
280
- });
281
- if (!allowed) {
282
- return { bulkAction: false, error: 'Access denied' };
283
- }
284
- }
285
593
  try {
594
+ if (action.hasAccess) {
595
+ const allowed = await action.hasAccess({
596
+ session: context.session,
597
+ context,
598
+ listKey: props.listKey,
599
+ });
600
+ if (!allowed) {
601
+ return { bulkAction: false, error: 'Access denied' };
602
+ }
603
+ }
286
604
  const result = await action.handler({
287
605
  listKey: props.listKey,
288
606
  ids: props.ids,
@@ -291,19 +609,10 @@ _resolveOutputChain) {
291
609
  return { bulkAction: true, message: result?.message };
292
610
  }
293
611
  catch (error) {
294
- if (error instanceof ValidationError || error instanceof DatabaseError) {
295
- return { bulkAction: false, error: error.message };
296
- }
297
- const dbError = parsePrismaError(error, listConfig);
298
- // A recognised Prisma error carries a user-safe, translated message.
299
- if (dbError instanceof DatabaseError) {
300
- return { bulkAction: false, error: dbError.message };
301
- }
302
- // Anything else is an unexpected handler bug whose raw `.message` could
303
- // leak internal detail to the client — log it server-side and return a
304
- // generic client-facing message instead.
305
- console.error(`Bulk action "${props.key}" on list "${props.listKey}" failed:`, error);
306
- return { bulkAction: false, error: 'Action failed' };
612
+ const failure = clientFailure(error, config, props.listKey, props.action, {
613
+ genericMessage: 'Action failed',
614
+ });
615
+ return { bulkAction: false, error: failure.error, code: failure.code };
307
616
  }
308
617
  }
309
618
  // Runs on the RELATED row (ADR-0018 boundary — see ServerActionProps above).
@@ -311,28 +620,119 @@ _resolveOutputChain) {
311
620
  // becomes `{ removed: false }` with a generic reason — never leaking whether
312
621
  // the row was denied or absent.
313
622
  if (props.action === 'removeRelated') {
623
+ const relatedId = parseId(props.listKey, props.id);
624
+ if (relatedId === null)
625
+ return { removed: false, error: 'Access denied or operation failed' };
314
626
  try {
315
627
  let result = null;
316
628
  if (props.mode === 'delete') {
317
- result = await model.delete({ where: { id: props.id } });
629
+ result = await model.delete({ where: { id: relatedId } });
318
630
  }
319
631
  else {
320
632
  // Disconnect: an UPDATE on the related list nulling its back-reference,
321
- // never a delete — the row itself survives. A to-one back-reference
322
- // disconnects with `true`; a to-many back-reference (many-to-many)
323
- // disconnects the specific parent by id.
633
+ // never a delete — the row itself survives. A non-owning back-reference
634
+ // (a to-many, the inverse half of a one-to-one, or a synthetic
635
+ // `from_<List>_<field>` back-relation) owns no foreign key to null, so
636
+ // removing that edge is deleting the junction row under its own delete
637
+ // access (`mode: 'delete'`), or nulling the field on the list that DOES
638
+ // own the column, not an update here (ADR-0050, ADR-0018 as amended).
324
639
  if (!props.field) {
325
640
  return { removed: false, error: 'Missing back-reference field for disconnect' };
326
641
  }
327
- const backRefField = listConfig.fields[props.field];
328
- const backRefIsMany = !!backRefField && 'many' in backRefField && backRefField.many === true;
329
- const disconnectValue = backRefIsMany
330
- ? { disconnect: { id: props.parentId } }
331
- : { disconnect: true };
332
- result = await model.update({
333
- where: { id: props.id },
334
- data: { [props.field]: disconnectValue },
335
- });
642
+ const backRef = classifyBackReference(props.listKey, props.field, listConfig, config);
643
+ if (backRef.kind === 'notRelationship') {
644
+ return {
645
+ removed: false,
646
+ error: `Field "${props.field}" on list "${props.listKey}" is not a relationship field`,
647
+ };
648
+ }
649
+ if (backRef.kind === 'nonOwning') {
650
+ return {
651
+ removed: false,
652
+ error: `Cannot unlink through "${props.field}": a non-owning back-reference owns no ` +
653
+ `foreign key to clear. Remove the row itself instead.`,
654
+ };
655
+ }
656
+ if (props.parentId === undefined) {
657
+ result = await model.update({
658
+ where: { id: relatedId },
659
+ data: { [props.field]: null },
660
+ });
661
+ }
662
+ else {
663
+ // Lock-then-compare (#1358): `props.parentId` is the caller's stale
664
+ // baseline for what this row points at. The contract names the
665
+ // owning foreign-key column `<field>Id` (relationship-input.ts),
666
+ // which is the key a bare read (no `include`) returns it under.
667
+ const fieldName = props.field;
668
+ const foreignKeyColumn = `${fieldName}Id`;
669
+ const parentListKey = backRef.field.ref.split('.')[0];
670
+ const expectedParentId = parseId(parentListKey, props.parentId);
671
+ if (expectedParentId === null) {
672
+ return { removed: false, error: 'Access denied or operation failed' };
673
+ }
674
+ const outcome = await transaction(async (tx) => {
675
+ const relatedList = tx.db[props.listKey];
676
+ // The secured read locks the row, but its columns are pre-lock and
677
+ // may be narrowed by Field Visibility, so the comparison value is
678
+ // re-read unscoped on the transaction's own handle (a second
679
+ // connection deadlocks the dev pool, ADR-0063). A stored link the
680
+ // session's own read cannot see is denied whatever `parentId` was
681
+ // sent, so a guess never confirms a hidden row (#1818).
682
+ const locked = await relatedList
683
+ .where({ id: { equals: relatedId } })
684
+ .forUpdate()
685
+ .first();
686
+ if (locked === null)
687
+ return 'denied';
688
+ const rawModel = engineContextOf(tx).ormHandle[props.listKey];
689
+ if (!isRawRowCollection(rawModel))
690
+ return 'denied';
691
+ const current = await withOrigin('engine', () => rawModel
692
+ .where((raw) => {
693
+ const predicate = raw['id']?.eq?.(relatedId);
694
+ if (predicate === undefined) {
695
+ throw new Error(`Cannot query "id" on list "${props.listKey}"`);
696
+ }
697
+ return predicate;
698
+ })
699
+ .select(foreignKeyColumn)
700
+ .first());
701
+ // `current` is absent only if the row vanished between the lock
702
+ // above and here, which the lock itself rules out — kept as a
703
+ // defensive branch rather than a non-null assertion.
704
+ if (current === null)
705
+ return 'denied';
706
+ const visible = await relatedList.where({ id: { equals: relatedId } }).first();
707
+ if (visible === null)
708
+ return 'denied';
709
+ const currentParentId = current[foreignKeyColumn];
710
+ if (currentParentId !== null && visible[foreignKeyColumn] === null) {
711
+ return 'denied';
712
+ }
713
+ if (currentParentId !== expectedParentId) {
714
+ return visible[foreignKeyColumn] === null
715
+ ? 'denied'
716
+ : 'conflict';
717
+ }
718
+ const updated = await relatedList.update({
719
+ where: { id: relatedId },
720
+ data: { [fieldName]: null },
721
+ });
722
+ return updated === null ? 'denied' : 'ok';
723
+ });
724
+ if (outcome === 'conflict') {
725
+ return {
726
+ removed: false,
727
+ error: 'This record was linked elsewhere since the form loaded, so the removal here ' +
728
+ 'was skipped. Reload to see its current link.',
729
+ };
730
+ }
731
+ if (outcome === 'denied') {
732
+ return { removed: false, error: 'Access denied or operation failed' };
733
+ }
734
+ return { removed: true };
735
+ }
336
736
  }
337
737
  if (result === null || result === undefined) {
338
738
  return { removed: false, error: 'Access denied or operation failed' };
@@ -340,20 +740,15 @@ _resolveOutputChain) {
340
740
  return { removed: true };
341
741
  }
342
742
  catch (error) {
343
- if (error instanceof ValidationError || error instanceof DatabaseError) {
344
- return { removed: false, error: error.message };
345
- }
346
- const dbError = parsePrismaError(error, listConfig);
347
- return { removed: false, error: dbError.message };
743
+ return { removed: false, ...clientFailure(error, config, props.listKey, props.action) };
348
744
  }
349
745
  }
350
746
  // Runs on the RELATED list (ADR-0018 boundary — see ServerActionProps above).
351
- // The back-reference to the parent is set here from `field`/`parentId` (a
352
- // to-one back-ref connects a single parent; a to-many back-ref, e.g.
353
- // many-to-many, connects the parent by id), so the client can never
354
- // re-target the link. Honours Silent failure: an access-denied create
355
- // returns `null`, surfaced as `{ created: false }` with a generic reason
356
- // (no denied-vs-absent leak).
747
+ // The back-reference to the parent is set here from `field`/`parentId`, so
748
+ // the client can never re-target the link. Only the foreign-key-owning side
749
+ // owns a column to hold it; a non-owning one is refused below. Honours
750
+ // Silent failure: an access-denied create returns `null`, surfaced as
751
+ // `{ created: false }` with a generic reason (no denied-vs-absent leak).
357
752
  if (props.action === 'createRelated') {
358
753
  try {
359
754
  // Defensive guard (hardening; unreachable from the drawer, which always
@@ -369,25 +764,36 @@ _resolveOutputChain) {
369
764
  }
370
765
  const data = { ...props.data };
371
766
  if (props.field && props.parentId) {
372
- const backRefField = listConfig.fields[props.field];
767
+ const backRef = classifyBackReference(props.listKey, props.field, listConfig, config);
373
768
  // The back-reference must name a relationship field on this list; a
374
769
  // non-relationship field would otherwise receive a nonsensical
375
770
  // { connect } value. Also hardening — the drawer only ever passes a
376
771
  // real relationship back-reference here.
377
- if (!backRefField || backRefField.type !== 'relationship') {
772
+ if (backRef.kind === 'notRelationship') {
378
773
  return {
379
774
  created: false,
380
775
  error: `Field "${props.field}" on list "${props.listKey}" is not a relationship field`,
381
776
  };
382
777
  }
383
- const backRefIsMany = 'many' in backRefField && backRefField.many === true;
778
+ // A non-owning back-reference (a to-many, the inverse half of a
779
+ // one-to-one, or a synthetic back-relation) owns no foreign key, so
780
+ // there is no column on the row being created for the parent to go
781
+ // in (ADR-0050).
782
+ if (backRef.kind === 'nonOwning') {
783
+ return {
784
+ created: false,
785
+ error: `Cannot preset "${props.field}": a non-owning back-reference owns no foreign key. ` +
786
+ `Link the parent from the side that holds the column.`,
787
+ };
788
+ }
789
+ const parentId = parseId(backRef.field.ref.split('.')[0], props.parentId);
790
+ if (parentId === null) {
791
+ return { created: false, error: 'Access denied or operation failed' };
792
+ }
384
793
  // The back-reference is set on the SERVER from the trusted parentId,
385
794
  // OVERWRITING any client-supplied data[field] spread in above, so a
386
- // hostile client can never re-target the link (a to-many back-ref
387
- // connects the parent by id).
388
- data[props.field] = backRefIsMany
389
- ? { connect: [{ id: props.parentId }] }
390
- : { connect: { id: props.parentId } };
795
+ // hostile client can never re-target the link.
796
+ data[props.field] = { connect: { id: parentId } };
391
797
  }
392
798
  const result = await model.create({ data });
393
799
  if (result === null || result === undefined) {
@@ -399,26 +805,108 @@ _resolveOutputChain) {
399
805
  return { created: true, id };
400
806
  }
401
807
  catch (error) {
402
- if (error instanceof ValidationError || error instanceof DatabaseError) {
403
- return { created: false, error: error.message, fieldErrors: error.fieldErrors };
808
+ return { created: false, ...clientFailure(error, config, props.listKey, props.action) };
809
+ }
810
+ }
811
+ // Adds one edge across an explicit junction list by creating the junction
812
+ // row (ADR-0050). Both foreign keys are `connect`s the SERVER composes from
813
+ // the resolved edge, so the payload carries no column of the client's
814
+ // choosing, and the reachability query behind each `connect` keeps an
815
+ // endpoint the caller cannot read indistinguishable from one that is not
816
+ // there. Honours Silent failure: a denied create on the junction list — the
817
+ // list this write is evaluated against, never the parent's — returns
818
+ // `null`, surfaced as `{ added: false }` with the same generic reason an
819
+ // unreachable endpoint gets.
820
+ if (props.action === 'addRelated') {
821
+ const edge = resolveJunctionEdge(config, props.listKey, props.field);
822
+ if (!edge) {
823
+ return {
824
+ added: false,
825
+ error: `Cannot link through "${props.listKey}.${props.field}": it is not an edge across an ` +
826
+ `explicit junction list. Write the related row against its own list instead.`,
827
+ };
828
+ }
829
+ const parentId = parseId(props.listKey, props.parentId);
830
+ const targetId = parseId(edge.targetListKey, props.targetId);
831
+ if (parentId === null || targetId === null) {
832
+ return { added: false, error: 'Access denied or operation failed' };
833
+ }
834
+ const junction = db[edge.junctionListKey];
835
+ try {
836
+ const result = await junction.create({
837
+ data: {
838
+ [edge.backReferenceField]: { connect: { id: parentId } },
839
+ [edge.targetField]: { connect: { id: targetId } },
840
+ },
841
+ });
842
+ if (result === null || result === undefined) {
843
+ return { added: false, error: 'Access denied or operation failed' };
404
844
  }
405
- const dbError = parsePrismaError(error, listConfig);
845
+ const id = typeof result === 'object' && result !== null && 'id' in result
846
+ ? String(result.id)
847
+ : undefined;
848
+ return { added: true, id };
849
+ }
850
+ catch (error) {
406
851
  return {
407
- created: false,
408
- error: dbError.message,
409
- fieldErrors: dbError instanceof DatabaseError ? dbError.fieldErrors : undefined,
852
+ added: false,
853
+ ...clientFailure(error, config, edge.junctionListKey, props.action, {
854
+ shownListKey: props.listKey,
855
+ }),
410
856
  };
411
857
  }
412
858
  }
859
+ // The write runs on the RELATED list, so that list's own update access and
860
+ // hooks decide it, never the parent's. Only the foreign-key-owning side
861
+ // owns a column to hold the link. Honours Silent failure: an access-denied
862
+ // update returns `null`, surfaced as `{ linked: false }` with a generic
863
+ // reason.
864
+ if (props.action === 'linkRelated') {
865
+ const backRef = classifyBackReference(props.listKey, props.field, listConfig, config);
866
+ if (backRef.kind === 'notRelationship') {
867
+ return {
868
+ linked: false,
869
+ error: `Field "${props.field}" on list "${props.listKey}" is not a relationship field`,
870
+ };
871
+ }
872
+ if (backRef.kind === 'nonOwning') {
873
+ return {
874
+ linked: false,
875
+ error: `Cannot link through "${props.field}": a non-owning back-reference owns no foreign key. ` +
876
+ `Link the parent from the side that holds the column.`,
877
+ };
878
+ }
879
+ const relatedId = parseId(props.listKey, props.id);
880
+ const parentId = parseId(backRef.field.ref.split('.')[0], props.parentId);
881
+ if (relatedId === null || parentId === null) {
882
+ return { linked: false, error: 'Access denied or operation failed' };
883
+ }
884
+ try {
885
+ const result = await model.update({
886
+ where: { id: relatedId },
887
+ data: { [props.field]: { connect: { id: parentId } } },
888
+ });
889
+ if (result === null || result === undefined) {
890
+ return { linked: false, error: 'Access denied or operation failed' };
891
+ }
892
+ return { linked: true };
893
+ }
894
+ catch (error) {
895
+ return { linked: false, ...clientFailure(error, config, props.listKey, props.action) };
896
+ }
897
+ }
413
898
  // Updates ONE scalar field on the RELATED row (ADR-0018 boundary — see
414
899
  // ServerActionProps above). Honours Silent failure: an access-denied update
415
900
  // returns `null`, surfaced as `{ updated: false }` with a generic reason (no
416
901
  // denied-vs-absent leak); a validation/db error surfaces its message and
417
902
  // fieldErrors so the cell can revert with a reason and show an inline error.
418
903
  if (props.action === 'updateRelated') {
904
+ const relatedId = parseId(props.listKey, props.id);
905
+ if (relatedId === null)
906
+ return { updated: false, error: 'Access denied or operation failed' };
419
907
  try {
420
908
  const result = await model.update({
421
- where: { id: props.id },
909
+ where: { id: relatedId },
422
910
  data: { [props.field]: props.value },
423
911
  });
424
912
  if (result === null || result === undefined) {
@@ -427,15 +915,7 @@ _resolveOutputChain) {
427
915
  return { updated: true };
428
916
  }
429
917
  catch (error) {
430
- if (error instanceof ValidationError || error instanceof DatabaseError) {
431
- return { updated: false, error: error.message, fieldErrors: error.fieldErrors };
432
- }
433
- const dbError = parsePrismaError(error, listConfig);
434
- return {
435
- updated: false,
436
- error: dbError.message,
437
- fieldErrors: dbError instanceof DatabaseError ? dbError.fieldErrors : undefined,
438
- };
918
+ return { updated: false, ...clientFailure(error, config, props.listKey, props.action) };
439
919
  }
440
920
  }
441
921
  try {
@@ -448,89 +928,62 @@ _resolveOutputChain) {
448
928
  };
449
929
  }
450
930
  const relatedListKey = fieldConfig.ref.split('.')[0];
931
+ const labelReadable = await isRelationshipLabelReadable(context, config, relatedListKey);
451
932
  const options = await getRelationshipOptions(context, config, relatedListKey, {
933
+ labelReadable,
452
934
  search: props.search,
453
935
  take: props.take,
454
936
  selectedIds: props.selectedIds,
455
937
  });
456
- return { success: true, data: options };
938
+ return { options };
457
939
  }
458
940
  let result = null;
459
941
  if (props.action === 'create') {
460
942
  result = await model.create({ data: props.data });
461
943
  }
462
- else if (props.action === 'update') {
463
- result = await model.update({
464
- where: { id: props.id },
465
- data: props.data,
466
- });
467
- }
468
- else if (props.action === 'delete') {
469
- result = await model.delete({
470
- where: { id: props.id },
471
- });
944
+ else if (props.action === 'update' || props.action === 'delete') {
945
+ const id = parseId(props.listKey, props.id);
946
+ if (id === null) {
947
+ return { success: false, error: 'Access denied or operation failed' };
948
+ }
949
+ result =
950
+ props.action === 'update'
951
+ ? await model.update({ where: { id }, data: props.data })
952
+ : await model.delete({ where: { id } });
472
953
  }
473
954
  // Check for access denial (null return from access-controlled operations)
474
- if (result === null) {
955
+ if (result === null || result === undefined) {
475
956
  return {
476
957
  success: false,
477
958
  error: 'Access denied or operation failed',
478
959
  };
479
960
  }
480
- return {
481
- success: true,
482
- data: result,
483
- };
961
+ return { success: true, data: { id: result.id } };
484
962
  }
485
963
  catch (error) {
486
- if (error instanceof ValidationError) {
487
- return {
488
- success: false,
489
- error: error.message,
490
- fieldErrors: error.fieldErrors,
491
- };
492
- }
493
- if (error instanceof DatabaseError) {
494
- return {
495
- success: false,
496
- error: error.message,
497
- fieldErrors: error.fieldErrors,
498
- };
499
- }
500
- const dbError = parsePrismaError(error, listConfig);
501
- if (dbError instanceof DatabaseError) {
502
- return {
503
- success: false,
504
- error: dbError.message,
505
- fieldErrors: dbError.fieldErrors,
506
- };
507
- }
508
- return {
509
- success: false,
510
- error: dbError.message,
511
- };
964
+ return { success: false, ...clientFailure(error, config, props.listKey, props.action) };
512
965
  }
513
966
  }
514
967
  // Bypasses access control; hooks and validation still run.
515
968
  function sudo() {
516
- return getContext(config, prisma, session, context.storage, true, undefined,
969
+ return getContext(config, ormHandle, session, context.storage, true, undefined,
517
970
  // ADR-0028: a sudo write issued from inside an owned transaction (e.g.
518
971
  // `tx.sudo().db.x.create()`) must still defer to that owner.
519
- context._transactionOwner,
520
- // #1176: carry the resolve chain forward so a `context.sudo()` called
521
- // from inside a `resolveOutput` hook keeps that hook's cycle-guard
522
- // chain (ADR-0023) rather than resetting to empty.
523
- context._resolveOutputChain);
972
+ context._transactionOwner, client, _unsafeTransaction,
973
+ // Carry the same base-client context forward (issue #1348) — sudo()
974
+ // derives a new context, not a new transaction boundary.
975
+ context._baseContext);
524
976
  }
525
977
  // Substitutes the session; access control and hooks still run against it
526
978
  // (orthogonal to `sudo`, so the receiver's sudo state is preserved).
527
979
  function withSession(newSession) {
528
- return getContext(config, prisma, newSession, context.storage, _isSudo, undefined,
980
+ return getContext(config, ormHandle, newSession, context.storage, _isSudo, undefined,
529
981
  // ADR-0028: a write issued from inside an owned transaction (e.g.
530
982
  // `tx.withSession(s).db.x.create()`) must still defer to that owner.
531
- context._transactionOwner,
532
- // #1176: see the identical comment in `sudo()` above.
533
- context._resolveOutputChain);
983
+ context._transactionOwner, client, _unsafeTransaction,
984
+ // Carry the same base-client context forward (issue #1348) — withSession()
985
+ // derives a new context, not a new transaction boundary.
986
+ context._baseContext);
534
987
  }
535
988
  // Interactive, hook-firing transaction (#614). See the `transaction` doc on
536
989
  // `StackContext` above for the atomicity/isolation/retry contract.
@@ -543,32 +996,68 @@ _resolveOutputChain) {
543
996
  // outcome once the callback (and any real transaction) has settled. A
544
997
  // `transaction()` nested inside another joins the outer owner's queue
545
998
  // rather than creating a second one.
546
- function transaction(fn, options) {
999
+ function transaction(fn) {
547
1000
  if (context._transactionOwner) {
548
- return fn(returned);
1001
+ return joinNested(fn, transactionFace(returned, lock, context._transactionOwner), context._transactionOwner);
549
1002
  }
550
1003
  const registry = new TransactionRegistry();
551
- const client = prisma;
552
- const settled = typeof client.$transaction !== 'function'
553
- ? // No interactive transaction available (plain client/mock, or already
554
- // inside one — see `TransactionCapable` above). Run directly: hook/
555
- // access semantics are identical, atomicity comes from the enclosing
556
- // transaction.
557
- fn(getContext(config, prisma, session, context.storage, _isSudo, context.plugins, registry, context._resolveOutputChain))
558
- : client.$transaction((tx) => fn(getContext(config, tx, session, context.storage, _isSudo, context.plugins, registry, context._resolveOutputChain)), options);
559
- return settleTransactionOwner(settled, registry);
1004
+ const ormClient = ormHandle;
1005
+ const settled = runTransactionBody(fn, registry, ormClient);
1006
+ return settleTransactionOwner(settled, registry, config);
1007
+ }
1008
+ function runTransactionBody(fn, registry, ormClient) {
1009
+ const child = (ormHandle, unsafeTransaction) => transactionFace(getContext(config, ormHandle, session, context.storage, _isSudo, context.plugins, registry, client, unsafeTransaction,
1010
+ // This transaction is opening fresh here, so its own base is this
1011
+ // context — or, if this context already carries one (defence in
1012
+ // depth; `context._transactionOwner` being unset here should
1013
+ // already imply it doesn't), that same base (issue #1348).
1014
+ context._baseContext ?? context), rowLockSeat(client, unsafeTransaction), registry);
1015
+ // Known limits: this branch hands `fn` a context whose `unsafe` is built
1016
+ // over the outer client, because a Prisma 7 transaction client carries no
1017
+ // `sql`/`orm` lanes to derive an `UnsafeTransactionScope` from. It is
1018
+ // unreachable while `$transaction` is a name no Prisma 8 object carries;
1019
+ // the moment the engine's handle becomes transaction-capable and takes
1020
+ // this branch, the scope has to be derived here too or `tx.unsafe` starts
1021
+ // executing outside the transaction it opened.
1022
+ if (typeof ormClient.$transaction === 'function') {
1023
+ return ormClient.$transaction(async (tx) => {
1024
+ const result = await fn(child(tx));
1025
+ throwIfPoisoned(registry);
1026
+ return result;
1027
+ });
1028
+ }
1029
+ // Prisma 8's transaction holds a pooled connection for the whole callback,
1030
+ // so the engine's handle is rebound to the transaction's own collections:
1031
+ // a `db` left on the outer handle would auto-commit outside the open
1032
+ // transaction, or wait forever for a second connection the dev database's
1033
+ // single-connection pool never frees (ADR-0056, ADR-0063).
1034
+ if (openTransaction !== undefined) {
1035
+ return openTransaction(async (opened) => {
1036
+ const result = await fn(child(opened.ormHandle, opened.unsafe));
1037
+ throwIfPoisoned(registry);
1038
+ if (!registry.hasReachedUnsafe)
1039
+ return result;
1040
+ await createLivenessProbe(client?.raw, opened.unsafe)?.().catch((aborted) => {
1041
+ throw new TransactionRolledBackError({ cause: registry.poisonCause ?? aborted });
1042
+ });
1043
+ return result;
1044
+ });
1045
+ }
1046
+ // Already inside a transaction someone else opened: run directly, because
1047
+ // hook and access semantics are identical and the atomicity comes from
1048
+ // that enclosing transaction (ADR-0028).
1049
+ if (_unsafeTransaction !== undefined) {
1050
+ return fn(child(ormHandle, _unsafeTransaction)).then((result) => {
1051
+ throwIfPoisoned(registry);
1052
+ return result;
1053
+ });
1054
+ }
1055
+ return Promise.reject(new TransactionUnavailableError());
560
1056
  }
561
1057
  const returned = {
562
- // The one place that legitimately knows `db` is shaped as the caller's
563
- // `TDb` says: `populateDbDelegate` above always builds the plain
564
- // `AccessControlledDB<TPrisma>` runtime shape, and a caller asking for a
565
- // richer description (e.g. the generated `CustomDB`) is asserting that
566
- // description is compatible with what actually comes back at runtime.
567
- // This is the single internal cast `TDb` exists to replace every
568
- // consumer-side `as unknown as` with (#1328).
569
1058
  db: db,
570
1059
  session,
571
- prisma,
1060
+ unsafe,
572
1061
  storage: context.storage,
573
1062
  plugins: context.plugins,
574
1063
  serverAction,
@@ -576,543 +1065,249 @@ _resolveOutputChain) {
576
1065
  withSession,
577
1066
  transaction,
578
1067
  _isSudo,
579
- // #1176: carried so a `StackContext` structurally satisfies `AccessContext`
580
- // and can be handed, unchanged, to the internal write-pipeline/hook
581
- // plumbing that a plain `AccessContext` was built for — see
582
- // `bindContextToTransaction` in `write-pipeline.ts`.
583
- _resolveOutputChain: context._resolveOutputChain,
584
- _transactionOwner: context._transactionOwner,
1068
+ [ENGINE_FACE]: context,
585
1069
  };
586
1070
  return returned;
587
1071
  }
1072
+ /**
1073
+ * Complete the normalisation the engine terminal started, for a write.
1074
+ *
1075
+ * A terminal classifies by SQLSTATE alone — it holds no config, so a `23505`
1076
+ * leaves it as a `UniqueConstraintViolation` carrying the constraint
1077
+ * name and the generic message. Resolving that name to the OpenSaas fields it
1078
+ * covers needs the generated constraint map, which is reached through the
1079
+ * config, so the write operations close the gap here (ADR-0042).
1080
+ *
1081
+ * Reads are not wrapped: no read raises a unique violation, and every other
1082
+ * driver failure is already final at the terminal.
1083
+ */
1084
+ function resolvingConstraints(operation, config) {
1085
+ return async (...args) => {
1086
+ try {
1087
+ return await operation(...args);
1088
+ }
1089
+ catch (error) {
1090
+ throw normalizeDatabaseError(error, config);
1091
+ }
1092
+ };
1093
+ }
588
1094
  /**
589
1095
  * Populate `target` with the access-controlled CRUD operations for every list,
590
- * each bound to `prisma` and `context`. Used both by {@link getContext} (at
1096
+ * each bound to `ormHandle` and `context`. Used both by {@link getContext} (at
591
1097
  * request setup) and by the Write Pipeline to rebuild a `db` delegate against a
592
1098
  * transaction client (ADR-0010), so a hook's `context.db` write participates in
593
1099
  * the same transaction.
594
1100
  *
595
- * The operations capture `prisma` at construction, so rebinding to a different
1101
+ * The operations capture `ormHandle` at construction, so rebinding to a different
596
1102
  * client (e.g. a transaction `tx`) requires rebuilding the delegate — which is
597
1103
  * exactly what this function enables.
598
1104
  */
599
- export function populateDbDelegate(target, config, prisma, context) {
1105
+ export function populateDbDelegate(target, config, ormHandle, context,
1106
+ /** The row-lock lane, on a transaction-bound context alone (ADR-0047). */
1107
+ lock) {
600
1108
  for (const [listName, listConfig] of Object.entries(config.lists)) {
601
- const dbKey = getDbKey(listName);
602
- const createOp = createCreate(listName, listConfig, prisma, context, config);
603
- const findManyOp = createFindMany(listName, listConfig, prisma, context, config);
604
- const updateOp = createUpdate(listName, listConfig, prisma, context, config);
1109
+ const createOp = resolvingConstraints(createCreate(listName, listConfig, ormHandle, context, config), config);
1110
+ const updateOp = resolvingConstraints(createUpdate(listName, listConfig, ormHandle, context, config), config);
605
1111
  const operations = {
606
- findUnique: createFindUnique(listName, listConfig, prisma, context, config),
607
- findMany: findManyOp,
608
- findFirst: createFindFirst(findManyOp),
609
1112
  create: createOp,
610
1113
  update: updateOp,
611
- delete: createDelete(listName, listConfig, prisma, context, config),
612
- count: createCount(listName, listConfig, prisma, context, config),
613
- createMany: createCreateMany(listName, listConfig, prisma, context, config, createOp),
614
- updateMany: createUpdateMany(listName, listConfig, prisma, context, config, findManyOp, updateOp),
1114
+ delete: resolvingConstraints(createDelete(listName, listConfig, ormHandle, context, config), config),
615
1115
  };
1116
+ const read = createSecuredRead({ listName, listConfig, ormHandle, context, config, lock });
616
1117
  if (isSingletonList(listConfig)) {
617
- operations.get = createGet(listName, listConfig, prisma, context, config, createOp);
1118
+ operations.get = resolvingConstraints(createGet(listName, listConfig, read, context, createOp), config);
1119
+ }
1120
+ else {
1121
+ operations.where = read.where;
1122
+ operations.orderBy = read.orderBy;
1123
+ operations.include = read.include;
1124
+ operations.select = read.select;
1125
+ operations.limit = read.limit;
1126
+ operations.offset = read.offset;
1127
+ operations.distinct = read.distinct;
1128
+ operations.distinctOn = read.distinctOn;
1129
+ operations.cursor = read.cursor;
1130
+ operations.forUpdate = read.forUpdate;
1131
+ operations.all = read.all;
1132
+ operations.first = read.first;
1133
+ operations.nearest = read.nearest;
1134
+ operations.aggregate = read.aggregate;
618
1135
  }
619
- target[dbKey] = operations;
1136
+ target[listName] = operations;
620
1137
  }
621
1138
  }
622
1139
  /**
623
- * Build a fresh access-controlled `db` delegate bound to `prisma` and `context`.
1140
+ * Build a fresh access-controlled `db` delegate bound to `ormHandle` and `context`.
624
1141
  * Convenience wrapper over {@link populateDbDelegate} returning a new object,
625
1142
  * used by the Write Pipeline to rebind `db` to a transaction client.
1143
+ *
1144
+ * The lock lane comes off `context._rowLock`, so a delegate rebuilt inside a
1145
+ * transaction keeps the `forUpdate()` its context already had (ADR-0047) — a
1146
+ * hook is a caller like any other. Its absence is the caller's statement that
1147
+ * this context is not the transaction's.
626
1148
  */
627
- export function buildDbDelegate(config, prisma, context) {
1149
+ export function buildDbDelegate(config, ormHandle, context) {
628
1150
  const db = {};
629
- populateDbDelegate(db, config, prisma, context);
1151
+ populateDbDelegate(db, config, ormHandle, context, context._rowLock);
630
1152
  return db;
631
1153
  }
632
- /**
633
- * Resolve the `include` (and declared-dependency provenance) a read should
634
- * use, preserving each existing path's exact shape — fragment / sudo /
635
- * caller include / bare (ADR-0024) — while folding declared dependencies
636
- * (`needs`, ADR-0025) into whichever of those the read is already using.
637
- *
638
- * A non-sudo fragment's own `include` and a non-sudo caller's `include` are
639
- * both folded and then scoped by `buildAccessScopedInclude` (ADR-0026) —
640
- * caller-directed, so a relation named nowhere in the folded tree never has
641
- * its list's `query` access evaluated at all (issue #1088: a fragment read
642
- * used to skip this walk entirely). A sudo caller's `include` (fragment or
643
- * not) is folded and used as-is, unscoped — sudo is unaffected. A bare read
644
- * stays on the exact ADR-0024 path — `include: undefined`, no related
645
- * `query` access evaluated — unless folding actually added something, which
646
- * only happens when a field on this list declares `needs`.
647
- *
648
- * Also returns the `FieldSelectionScope` a fragment's own field selection
649
- * produces (ADR-0027), so the caller can pass it to `filterReadableFields`
650
- * and make computation itself projection-aware, not only the fold above.
651
- * `undefined` for every non-fragment path: a caller `include` (sudo or not)
652
- * and a bare read both mean "compute every field," matching what they
653
- * already fetch.
654
- *
655
- * Also returns `toOneAccessFilters` — the to-one relations `buildAccessScopedInclude`
656
- * flagged as needing a post-query existence check rather than a Prisma-side
657
- * `where` (issue #974). Only a non-sudo fragment or caller-include read can
658
- * produce a non-empty tree: those are the only paths that evaluate a related
659
- * list's `query` access at all. A sudo read and a bare read always return an
660
- * empty tree.
661
- */
662
- async function resolveReadInclude(callerInclude, fragmentFields, listName,
663
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
664
- listConfig, context, config) {
665
- if (fragmentFields !== undefined) {
666
- const fragmentInclude = buildInclude(fragmentFields) ?? undefined;
667
- const selection = buildFieldSelectionScope(fragmentFields);
668
- const folded = foldDeclaredDependencies(fragmentInclude, listConfig.fields, config, listName, [listName], selection);
669
- if (context._isSudo || !folded.include) {
670
- return {
671
- ...folded,
672
- selection,
673
- toOneAccessFilters: emptyToOneAccessFilterTree(),
674
- countDenials: emptyCountAccessDenialTree(),
675
- };
676
- }
677
- const { include, toOneAccessFilters, countDenials } = await buildAccessScopedInclude(folded.include, listConfig.fields, { session: context.session, context }, config, listName);
678
- return {
679
- include,
680
- declaredOnly: folded.declaredOnly,
681
- selection,
682
- toOneAccessFilters,
683
- countDenials,
684
- };
685
- }
686
- if (context._isSudo) {
687
- const folded = foldDeclaredDependencies(callerInclude, listConfig.fields, config, listName);
688
- return {
689
- ...folded,
690
- selection: undefined,
691
- toOneAccessFilters: emptyToOneAccessFilterTree(),
692
- countDenials: emptyCountAccessDenialTree(),
693
- };
1154
+ const WRITE_ARG_KEYS = {
1155
+ create: ['data'],
1156
+ update: ['where', 'data'],
1157
+ delete: ['where'],
1158
+ };
1159
+ function assertWriteArgs(args, listName, operation, isSingleton) {
1160
+ const allowed = WRITE_ARG_KEYS[operation];
1161
+ if (args === null || typeof args !== 'object') {
1162
+ throw new ValidationError([`${operation}() on "${listName}" takes an argument object with ${allowed.join(', ')}.`], {});
694
1163
  }
695
- const folded = foldDeclaredDependencies(callerInclude, listConfig.fields, config, listName);
696
- if (!folded.include) {
697
- return {
698
- ...folded,
699
- selection: undefined,
700
- toOneAccessFilters: emptyToOneAccessFilterTree(),
701
- countDenials: emptyCountAccessDenialTree(),
702
- };
1164
+ for (const [key, value] of Object.entries(args)) {
1165
+ if (allowed.includes(key) || value === undefined)
1166
+ continue;
1167
+ const readBack = isSingleton
1168
+ ? `context.db.${listName}.get({ include: { … } }) (a singleton has no select)`
1169
+ : `context.db.${listName}.where({ id: { equals: row.id } }).${key}(…).first()`;
1170
+ const reason = key === 'select' || key === 'include'
1171
+ ? `\`${key}\` is not supported on a write. Write first, then read the row back with ` +
1172
+ `${readBack}, inside context.transaction() when the two must be atomic.`
1173
+ : `\`${key}\` is not an argument of ${operation}(); it takes ${allowed.join(', ')}.`;
1174
+ throw new ValidationError([`${operation}() on "${listName}": ${reason}`], {});
703
1175
  }
704
- const { include, toOneAccessFilters, countDenials } = await buildAccessScopedInclude(folded.include, listConfig.fields, { session: context.session, context }, config, listName);
705
- return {
706
- include,
707
- declaredOnly: folded.declaredOnly,
708
- selection: undefined,
709
- toOneAccessFilters,
710
- countDenials,
711
- };
712
- }
713
- function createFindUnique(listName,
714
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
715
- listConfig, prisma, context, config) {
716
- return async (args) => {
717
- warnIfSelectIgnored(args, listName, 'findUnique');
718
- // Runs first, before the access check below — a non-unique `where` is a
719
- // caller-shape error (see `assertUniqueWhere`), not an access denial. The
720
- // generated `<List>FindUniqueArgs` only Omits `select`/`include` from
721
- // Prisma's own type, so `where` stays `<List>WhereUniqueInput` — this
722
- // runtime guard backstops untyped callers.
723
- assertUniqueWhere(args.where, getUniqueWhereKeys(listConfig), listName);
724
- let where = args.where;
725
- if (!context._isSudo) {
726
- const queryAccess = listConfig.access?.operation?.query;
727
- const accessResult = await checkAccess(queryAccess, {
728
- session: context.session,
729
- context,
730
- });
731
- if (accessResult === false) {
732
- return null;
733
- }
734
- const mergedWhere = mergeFilters(args.where, accessResult);
735
- if (mergedWhere === null) {
736
- return null;
737
- }
738
- where = mergedWhere;
739
- }
740
- // Access control still runs via filterReadableFields even though a
741
- // fragment drives `include`; the fragment only narrows which fields come back.
742
- const fragment = isFragment(args.query) ? args.query : null;
743
- // Resolve `include`, folding any declared dependencies (`needs`,
744
- // ADR-0025) in alongside whatever the fragment/caller/sudo/bare path
745
- // already produces — see `resolveReadInclude`'s doc comment.
746
- let { include, declaredOnly, selection, toOneAccessFilters, countDenials } = await resolveReadInclude(args.include, fragment ? fragment._fields : undefined, listName, listConfig, context, config);
747
- // Virtual fields have no database column. Whichever path produced
748
- // `include` (fragment, access-controlled merge, or sudo passthrough), a
749
- // virtual key must never reach Prisma — it would throw "Unknown field"
750
- // (#628). Below, `filterReadableFields` computes a virtual field's value
751
- // exactly when `selection` says the read is going to return it (ADR-0027)
752
- // — every one of them for a bare/`include`-based read (`selection` is
753
- // `undefined`), only the ones a fragment named otherwise.
754
- include = stripVirtualFieldsFromInclude(include, listConfig.fields, config);
755
- // Access Prisma model dynamically - required because model names are generated at runtime
756
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
757
- const model = prisma[getDbKey(listName)];
758
- const item = await model.findFirst({
759
- where,
760
- include,
761
- });
762
- if (!item) {
763
- return null;
764
- }
765
- // Resolve which of the to-one relations flagged by `toOneAccessFilters`
766
- // actually survive their related list's `query` access (issue #974) —
767
- // one batched existence check per relation, before field visibility runs.
768
- const toOneVisibility = await resolveToOneAccessVisibility([item], toOneAccessFilters, {
769
- session: context.session,
770
- context,
771
- });
772
- // Pass sudo flag through context to skip field-level access checks
773
- const filtered = await filterReadableFields(item, listConfig.fields, {
774
- session: context.session,
775
- context: { ...context, _isSudo: context._isSudo },
776
- }, config, 0, listName, declaredOnly, selection, toOneVisibility, countDenials);
777
- if (fragment) {
778
- return pickFields(filtered, fragment._fields);
779
- }
780
- return filtered;
781
- };
782
- }
783
- function createFindMany(listName,
784
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
785
- listConfig, prisma, context, config) {
786
- return async (args) => {
787
- warnIfSelectIgnored(args, listName, 'findMany');
788
- // Singleton misuse throws rather than silently returning `[]` — unlike an
789
- // access denial, this is a caller-shape error.
790
- if (isSingletonList(listConfig)) {
791
- throw new ValidationError([`Cannot use findMany: ${listName} is a singleton list. Use get() instead.`], {});
792
- }
793
- // Check query access first (skip if sudo mode) — this MUST run before the
794
- // #912/#915 where/orderBy validation below. See the comment there for why.
795
- let where = args?.where;
796
- if (!context._isSudo) {
797
- const queryAccess = listConfig.access?.operation?.query;
798
- const accessResult = await checkAccess(queryAccess, {
799
- session: context.session,
800
- context,
801
- });
802
- if (accessResult === false) {
803
- return [];
804
- }
805
- // #912 — reject a `where`/`orderBy` key the list config doesn't declare
806
- // (e.g. a Prisma-generated back-relation), and #915 — reject one naming
807
- // a field this session cannot READ (closing a probe via a `count()`
808
- // that varies with the withheld value, or an `orderBy` that leaks
809
- // relative ordering). Both run only now that the caller is known to
810
- // have SOME access to the list (`accessResult !== false`): the thrown
811
- // errors name the offending key, and running them before the access
812
- // check above would let a caller with ZERO access to the list learn a
813
- // field's name and read-gating status from the error message alone —
814
- // turning the validation itself into the kind of oracle #915 closes.
815
- // `sudo` bypasses this whole branch, matching the write path.
816
- validateQueryKeys({
817
- where: args?.where,
818
- orderBy: args?.orderBy,
819
- listConfig,
820
- listName,
821
- config,
822
- isSudo: false,
823
- });
824
- await validateQueryFieldReadAccess({
825
- where: args?.where,
826
- orderBy: args?.orderBy,
827
- listConfig,
828
- listName,
829
- session: context.session,
830
- context,
831
- isSudo: false,
832
- });
833
- // #916 — scope every relation filter nested in `where`
834
- // (`some`/`every`/`none`/`is`/`isNot`) by the RELATED list's own `query`
835
- // access, recursing through every hop of a chain — the `where`
836
- // counterpart to how `include` is already scoped below via
837
- // `buildAccessScopedInclude`. Runs after the checks above for the same
838
- // ordering reason: only once the caller is known to have SOME access to
839
- // THIS list.
840
- const scopedWhere = args?.where
841
- ? (await buildAccessScopedWhere(args.where, listConfig, listName, config, {
842
- session: context.session,
843
- context,
844
- }))
845
- : args?.where;
846
- const mergedWhere = mergeFilters(scopedWhere, accessResult);
847
- if (mergedWhere === null) {
848
- return [];
849
- }
850
- where = mergedWhere;
851
- }
852
- const fragment = isFragment(args?.query) ? args.query : null;
853
- // Resolve `include`, folding any declared dependencies (`needs`,
854
- // ADR-0025) in alongside whatever the fragment/caller/sudo/bare path
855
- // already produces — see `resolveReadInclude`'s doc comment.
856
- let { include, declaredOnly, selection, toOneAccessFilters, countDenials } = await resolveReadInclude(args?.include, fragment ? fragment._fields : undefined, listName, listConfig, context, config);
857
- // Strips virtual keys from `include` before the Prisma call — see the
858
- // `createFindUnique` comment above for why (#628, ADR-0027).
859
- include = stripVirtualFieldsFromInclude(include, listConfig.fields, config);
860
- // Access Prisma model dynamically - required because model names are generated at runtime
861
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
862
- const model = prisma[getDbKey(listName)];
863
- const items = await model.findMany({
864
- where,
865
- orderBy: args?.orderBy,
866
- take: args?.take,
867
- skip: args?.skip,
868
- include,
869
- });
870
- // Resolve which of the to-one relations flagged by `toOneAccessFilters`
871
- // actually survive their related list's `query` access (issue #974) —
872
- // ONE batched existence check per relation across every row in `items`,
873
- // before field visibility runs on any of them.
874
- const toOneVisibility = await resolveToOneAccessVisibility(items, toOneAccessFilters, {
875
- session: context.session,
876
- context,
877
- });
878
- // Pass sudo flag through context to skip field-level access checks
879
- const filtered = await Promise.all(items.map((item) => filterReadableFields(item, listConfig.fields, {
880
- session: context.session,
881
- context: { ...context, _isSudo: context._isSudo },
882
- }, config, 0, listName, declaredOnly, selection, toOneVisibility, countDenials)));
883
- if (fragment) {
884
- return filtered.map((item) => pickFields(item, fragment._fields));
885
- }
886
- return filtered;
887
- };
888
- }
889
- /**
890
- * Create findFirst operation with access control.
891
- *
892
- * findFirst is sugar over the access-controlled findMany: it runs the exact same
893
- * query-access checks and access-controlled include building as findMany, then
894
- * returns the first matching row (or null when nothing matches). This introduces
895
- * no new access surface — it inherits findMany's silent-failure contract (an
896
- * access-denied query yields `[]`, which becomes `null` here).
897
- */
898
- function createFindFirst(findManyOp) {
899
- return async (args) => {
900
- const result = await findManyOp({ ...args, take: 1 });
901
- return result[0] ?? null;
902
- };
903
1176
  }
904
1177
  function createCreate(listName,
905
1178
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
906
- listConfig, prisma, context, config) {
1179
+ listConfig, ormHandle, context, config) {
907
1180
  // Thin adapter over the Write Pipeline: pick the create strategy, run the
908
1181
  // canonical secured write sequence, return its result.
909
1182
  return async (args) => {
1183
+ assertWriteArgs(args, listName, 'create', isSingletonList(listConfig));
910
1184
  return runWritePipeline({
911
1185
  listName,
912
1186
  listConfig,
913
- prisma,
1187
+ ormHandle,
914
1188
  context,
915
1189
  config,
916
1190
  inputData: args.data,
917
- strategy: createWriteStrategy(listName, listConfig, context),
1191
+ strategy: createWriteStrategy(listName, listConfig),
918
1192
  });
919
1193
  };
920
1194
  }
921
- // Runs create in a loop (not Prisma's native createMany) so every item still
922
- // gets its own hooks and access control.
923
- function createCreateMany(listName,
924
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
925
- listConfig, prisma, context, config,
926
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
927
- createFn) {
928
- return async (args) => {
929
- const results = [];
930
- for (const item of args.data) {
931
- const result = await createFn({ data: item });
932
- results.push(result);
933
- }
934
- return results;
935
- };
936
- }
937
1195
  function createUpdate(listName,
938
1196
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
939
- listConfig, prisma, context, config) {
1197
+ listConfig, ormHandle, context, config) {
940
1198
  // Thin adapter over the Write Pipeline: pick the update strategy, run the
941
1199
  // canonical secured write sequence, return its result.
942
1200
  return async (args) => {
1201
+ // Runs before the pipeline's access gate — a `where` the engine cannot
1202
+ // lower is the caller's own shape error, not a denial.
1203
+ assertWriteArgs(args, listName, 'update', isSingletonList(listConfig));
1204
+ assertIdentityWhere(args.where, listName, 'update');
943
1205
  return runWritePipeline({
944
1206
  listName,
945
1207
  listConfig,
946
- prisma,
1208
+ ormHandle,
947
1209
  context,
948
1210
  config,
949
1211
  inputData: args.data,
950
- strategy: updateWriteStrategy(listConfig, context, args.where),
1212
+ strategy: updateWriteStrategy(listName, listConfig, config, args.where),
951
1213
  });
952
1214
  };
953
1215
  }
954
- // Finds matching records, then updates each individually (not Prisma's native
955
- // updateMany) so every item still gets its own hooks and access control.
956
- function createUpdateMany(listName,
957
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
958
- listConfig, prisma, context, config,
959
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
960
- findManyFn,
961
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
962
- updateFn) {
963
- return async (args) => {
964
- const items = await findManyFn({ where: args.where });
965
- const results = [];
966
- for (const item of items) {
967
- const result = await updateFn({ where: { id: item.id }, data: args.data });
968
- results.push(result);
969
- }
970
- return results;
971
- };
972
- }
973
1216
  function createDelete(listName,
974
1217
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
975
- listConfig, prisma, context, config) {
1218
+ listConfig, ormHandle, context, config) {
976
1219
  // Thin adapter over the Write Pipeline: pick the delete strategy, run the
977
1220
  // canonical secured write sequence, return its result.
978
1221
  return async (args) => {
1222
+ assertWriteArgs(args, listName, 'delete', isSingletonList(listConfig));
1223
+ assertIdentityWhere(args.where, listName, 'delete');
979
1224
  return runWritePipeline({
980
1225
  listName,
981
1226
  listConfig,
982
- prisma,
1227
+ ormHandle,
983
1228
  context,
984
1229
  config,
985
1230
  inputData: undefined,
986
- strategy: deleteWriteStrategy(listName, listConfig, context, args.where),
1231
+ strategy: deleteWriteStrategy(listName, listConfig, config, args.where),
987
1232
  });
988
1233
  };
989
1234
  }
990
- function createCount(listName,
991
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
992
- listConfig, prisma, context, config) {
993
- return async (args) => {
994
- // Check query access first (skip if sudo mode) — this MUST run before the
995
- // #912/#915 where validation below. See the comment there for why.
996
- let where = args?.where;
997
- if (!context._isSudo) {
998
- const queryAccess = listConfig.access?.operation?.query;
999
- const accessResult = await checkAccess(queryAccess, {
1000
- session: context.session,
1001
- context,
1002
- });
1003
- if (accessResult === false) {
1004
- return 0;
1005
- }
1006
- // #912 — reject a `where` key the list config doesn't declare (e.g. a
1007
- // Prisma-generated back-relation), and #915 — reject one naming a field
1008
- // this session cannot READ. `count` leaks the most cleanly of any read
1009
- // op — a bare count answers a predicate with no rows returned at all —
1010
- // so it gets the same reject, not a lesser one. Both run only now that
1011
- // the caller is known to have SOME access to the list (`accessResult
1012
- // !== false`) — see the identical comment in `createFindMany` for why
1013
- // that ordering matters: running them before the access check would
1014
- // let a fully-denied caller learn a field's name and read-gating
1015
- // status from the thrown error alone. `sudo` bypasses this whole
1016
- // branch, matching the write path.
1017
- validateQueryKeys({
1018
- where: args?.where,
1019
- listConfig,
1020
- listName,
1021
- config,
1022
- isSudo: false,
1023
- });
1024
- await validateQueryFieldReadAccess({
1025
- where: args?.where,
1026
- listConfig,
1027
- listName,
1028
- session: context.session,
1029
- context,
1030
- isSudo: false,
1031
- });
1032
- // #916 — scope every relation filter nested in `where` by the RELATED
1033
- // list's own `query` access. See the identical comment in
1034
- // `createFindMany` for why this runs here, in this order.
1035
- const scopedWhere = args?.where
1036
- ? (await buildAccessScopedWhere(args.where, listConfig, listName, config, {
1037
- session: context.session,
1038
- context,
1039
- }))
1040
- : args?.where;
1041
- const mergedWhere = mergeFilters(scopedWhere, accessResult);
1042
- if (mergedWhere === null) {
1043
- return 0;
1044
- }
1045
- where = mergedWhere;
1046
- }
1047
- // Access Prisma model dynamically - required because model names are generated at runtime
1048
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1049
- const model = prisma[getDbKey(listName)];
1050
- const count = await model.count({
1051
- where,
1052
- });
1053
- return count;
1054
- };
1235
+ /**
1236
+ * A singleton's `get({ include })` has no refinement to hand a nested shape
1237
+ * to: there is one row, so `where`/`orderBy`/`take` on a related list have
1238
+ * nothing to scope against. A non-boolean entry — `{ posts: { take: 5 } }` —
1239
+ * used to be treated as truthy and include the relation whole, silently
1240
+ * discarding the bound the caller wrote. Refuse it instead of guessing at
1241
+ * semantics for it (issue #1371).
1242
+ */
1243
+ function assertBooleanInclude(include, listName) {
1244
+ if (!include)
1245
+ return;
1246
+ for (const [key, value] of Object.entries(include)) {
1247
+ if (typeof value === 'boolean')
1248
+ continue;
1249
+ throw new ValidationError([
1250
+ `get() on "${listName}" received a non-boolean value for include.${key}. A singleton's ` +
1251
+ `get() accepts only \`true\`/\`false\` per relation — there is one row, so a nested ` +
1252
+ `refinement (\`where\`, \`take\`, \`select\`, …) has nothing to scope. Pass ` +
1253
+ `\`{ ${key}: true }\` to include the relation whole.`,
1254
+ ], {});
1255
+ }
1055
1256
  }
1257
+ /**
1258
+ * A singleton's read. The composed read is not offered on a singleton
1259
+ * (`populateDbDelegate` wires it in the other branch), but the engine drives it
1260
+ * here: `get()` resolves the one row through the same secured path an ordinary
1261
+ * list reads through, so operation access, the Access Filter, Field Visibility
1262
+ * and the related lists' own `query` access are the composed read's and not a
1263
+ * second copy of them.
1264
+ *
1265
+ * `null` from the read is denied-or-absent, so the auto-create below runs only
1266
+ * once the read has answered nothing — a denied session gets `null`, not a row.
1267
+ *
1268
+ * Known limits: auto-create fires only for a `query` rule that answered a
1269
+ * strict `true`, or under `sudo`. A rule that answered a filter scopes the read
1270
+ * rather than opening it, and there is no row yet to test that filter against,
1271
+ * so the create is refused and `get()` answers `null` — the same `null` a
1272
+ * denied or an absent row answers with.
1273
+ */
1056
1274
  function createGet(listName,
1057
1275
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1058
- listConfig, prisma, context, config,
1059
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1060
- createFn) {
1276
+ listConfig, read, context, createFn) {
1061
1277
  return async (args) => {
1062
1278
  warnIfSelectIgnored(args, listName, 'get');
1063
- // Access Prisma model dynamically - required because model names are generated at runtime
1064
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1065
- const model = prisma[getDbKey(listName)];
1066
- let where = {};
1279
+ assertBooleanInclude(args?.include, listName);
1280
+ const scoped = Object.entries(args?.include ?? {}).reduce((query, [name, requested]) => (requested ? query.include(name) : query), read);
1281
+ const item = await scoped.first();
1282
+ if (item)
1283
+ return item;
1284
+ if (!shouldAutoCreate(listConfig))
1285
+ return null;
1286
+ // `first()` conflates denied with absent, and auto-create must fire only on
1287
+ // absent — a denied session that provoked a create would both write a row it
1288
+ // may not read and turn the read's silence into an observable side effect.
1289
+ // Only a strict `true` clears the create: a filter scopes rather than opens,
1290
+ // and `false`, a missing rule and anything else are denials. This is the one
1291
+ // place the query rule is consulted directly; the read above owns every
1292
+ // other use of it.
1067
1293
  if (!context._isSudo) {
1068
- const queryAccess = listConfig.access?.operation?.query;
1069
- const accessResult = await checkAccess(queryAccess, {
1294
+ const readable = await checkAccess(listConfig.access?.operation?.query, {
1070
1295
  session: context.session,
1071
1296
  context,
1072
1297
  });
1073
- if (accessResult === false) {
1298
+ if (readable !== true)
1074
1299
  return null;
1075
- }
1076
- // A singleton has no per-record `where`, so the access filter (if any) is
1077
- // the whole `where`.
1078
- if (accessResult && typeof accessResult === 'object') {
1079
- where = accessResult;
1080
- }
1081
1300
  }
1082
- // Access control still runs via filterReadableFields even though a
1083
- // fragment drives `include`; the fragment only narrows which fields come back.
1084
- const fragment = isFragment(args?.query) ? args.query : null;
1085
- // Resolve `include`, folding any declared dependencies (`needs`,
1086
- // ADR-0025) in alongside whatever the fragment/caller/sudo/bare path
1087
- // already produces — see `resolveReadInclude`'s doc comment.
1088
- let { include, declaredOnly, selection, toOneAccessFilters, countDenials } = await resolveReadInclude(args?.include, fragment ? fragment._fields : undefined, listName, listConfig, context, config);
1089
- // Virtual fields have no database column and must never reach Prisma (#628).
1090
- include = stripVirtualFieldsFromInclude(include, listConfig.fields, config);
1091
- const item = await model.findFirst({
1092
- where,
1093
- include,
1094
- });
1095
- if (item) {
1096
- // Resolve which of the to-one relations flagged by `toOneAccessFilters`
1097
- // actually survive their related list's `query` access (issue #974).
1098
- const toOneVisibility = await resolveToOneAccessVisibility([item], toOneAccessFilters, {
1099
- session: context.session,
1100
- context,
1101
- });
1102
- const filtered = await filterReadableFields(item, listConfig.fields, {
1103
- session: context.session,
1104
- context: { ...context, _isSudo: context._isSudo },
1105
- }, config, 0, listName, declaredOnly, selection, toOneVisibility, countDenials);
1106
- if (fragment) {
1107
- return pickFields(filtered, fragment._fields);
1108
- }
1109
- return filtered;
1301
+ try {
1302
+ await createFn({ data: {} });
1110
1303
  }
1111
- if (shouldAutoCreate(listConfig)) {
1112
- const defaultData = getDefaultData(listConfig);
1113
- return await createFn({ data: defaultData });
1304
+ catch (error) {
1305
+ const raced = await scoped.first().catch(() => null);
1306
+ if (raced)
1307
+ return raced;
1308
+ throw error;
1114
1309
  }
1115
- return null;
1310
+ return await scoped.first();
1116
1311
  };
1117
1312
  }
1118
1313
  //# sourceMappingURL=index.js.map