@opensaas/stack-core 0.43.0 → 0.44.0-alpha.1

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 +2720 -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 +966 -614
  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 +540 -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 +282 -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 +135 -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 +457 -677
  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 +221 -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,1737 +0,0 @@
1
- import type { OpenSaasConfig, ListConfig } from '../config/types.js'
2
- import type { Session, AccessContext, AccessControlledDB, StorageUtils } from '../access/index.js'
3
- import {
4
- checkAccess,
5
- mergeFilters,
6
- filterReadableFields,
7
- buildAccessScopedInclude,
8
- buildAccessScopedWhere,
9
- stripVirtualFieldsFromInclude,
10
- foldDeclaredDependencies,
11
- validateQueryKeys,
12
- validateQueryFieldReadAccess,
13
- resolveToOneAccessVisibility,
14
- emptyToOneAccessFilterTree,
15
- emptyCountAccessDenialTree,
16
- } from '../access/index.js'
17
- import type {
18
- DeclaredOnlyTree,
19
- ToOneAccessFilterTree,
20
- CountAccessDenialTree,
21
- } from '../access/index.js'
22
- import { ValidationError, DatabaseError } from '../hooks/index.js'
23
- import { getDbKey } from '../lib/case-utils.js'
24
- import { uniqueConstraintOf } from '../lib/prisma-errors.js'
25
- import type { PrismaClientLike } from '../access/types.js'
26
- import { buildInclude, pickFields, isFragment, buildFieldSelectionScope } from '../query/index.js'
27
- import type { FieldSelection, FieldSelectionScope } from '../query/index.js'
28
- import { getRelationshipOptions } from '../query/relationship-options.js'
29
- import {
30
- runWritePipeline,
31
- createWriteStrategy,
32
- updateWriteStrategy,
33
- deleteWriteStrategy,
34
- } from './write-pipeline.js'
35
- import { AfterTransactionError } from './transaction-boundary.js'
36
- import { TransactionRegistry } from '../access/transaction-registry.js'
37
- import type { TransactionSettleOutcome } from '../access/transaction-registry.js'
38
-
39
- export type ServerActionProps =
40
- | { listKey: string; action: 'create'; data: Record<string, unknown> }
41
- | { listKey: string; action: 'update'; id: string; data: Record<string, unknown> }
42
- | { listKey: string; action: 'delete'; id: string }
43
- | { listKey: string; action: 'bulkDelete'; ids: string[] }
44
- // Custom list-specific bulk action (issue #736). `key` names an action
45
- // declared in the list's `ui.listView.bulkActions`; the client sends only
46
- // this serialisable `{ key, ids }` and the server-side `handler` (never
47
- // serialised) is looked up by `key`. Returns a distinct `{ bulkAction,
48
- // message? }` shape, never `success`, so a redirect-on-`success` wrapper
49
- // does not hijack it.
50
- | { listKey: string; action: 'bulkAction'; key: string; ids: string[] }
51
- // Relationship-table row removal (ADR-0018, #739). `listKey`/`id` target the
52
- // RELATED row, so the related list's own access control and hooks apply —
53
- // never the parent's. The other relationship-table actions below share this
54
- // boundary. `mode: 'disconnect'` unlinks the row by disconnecting its
55
- // back-reference (`field`; `parentId` is needed only when that back-reference
56
- // is to-many, e.g. a many-to-many join) without deleting it; `mode: 'delete'`
57
- // truly deletes the row. Returns a distinct `{ removed }` shape, never
58
- // `success`, so a UI wrapper that redirects on `success` does not hijack an
59
- // in-place row removal.
60
- | {
61
- listKey: string
62
- action: 'removeRelated'
63
- mode: 'disconnect' | 'delete'
64
- id: string
65
- field?: string
66
- parentId?: string
67
- }
68
- // Relationship-table inline cell edit (issue #737); same ADR-0018 boundary
69
- // as `removeRelated` — `listKey`/`id` target the RELATED row. Returns a
70
- // distinct `{ updated }` shape, never `success`, so a UI wrapper that
71
- // redirects on `success` does not hijack an in-place cell edit.
72
- | {
73
- listKey: string
74
- action: 'updateRelated'
75
- id: string
76
- field: string
77
- value: unknown
78
- }
79
- // Relationship-table pre-linked create (issue #738); same ADR-0018 boundary
80
- // as `removeRelated` — `listKey` targets the RELATED list. The back-reference
81
- // to the parent is set on the SERVER from `field`/`parentId`, never trusted
82
- // from `data`, so a hostile client cannot re-target the link. Returns a
83
- // distinct `{ created }` shape, never `success`, so a UI wrapper that
84
- // redirects on `success` does not hijack an in-place create.
85
- | {
86
- listKey: string
87
- action: 'createRelated'
88
- data: Record<string, unknown>
89
- field?: string
90
- parentId?: string
91
- }
92
- | {
93
- listKey: string
94
- action: 'relationshipOptions'
95
- field: string
96
- search?: string
97
- take?: number
98
- selectedIds?: string[]
99
- }
100
-
101
- const selectWarnings = new Set<string>()
102
-
103
- /**
104
- * Warn once per (list, operation) when a caller passes `select` to a read op
105
- * that ignores it. See "Narrowing Reads" in packages/core/CLAUDE.md.
106
- */
107
- function warnIfSelectIgnored(
108
- args: { select?: unknown } | undefined,
109
- listName: string,
110
- operation: string,
111
- ): void {
112
- if (!args || args.select === undefined) return
113
-
114
- const key = `${listName}.${operation}`
115
- if (selectWarnings.has(key)) return
116
- selectWarnings.add(key)
117
-
118
- console.warn(
119
- `[@opensaas/stack-core] \`select\` is ignored by context.db.${getDbKey(listName)}.${operation}() ` +
120
- `and the full (access-filtered) record is returned. ` +
121
- `Narrow a read with \`include\` or a fragment \`query\` instead. ` +
122
- `See https://stack.opensaas.au/docs/concepts/queries`,
123
- )
124
- }
125
-
126
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
127
- function isSingletonList(listConfig: ListConfig<any>): boolean {
128
- return !!listConfig.isSingleton
129
- }
130
-
131
- /**
132
- * Compute the set of single-field unique selectors a `findUnique` `where` may be
133
- * keyed by, derived from what the list config exposes at runtime: `id`, plus any
134
- * field declared `isIndexed: 'unique'` — for a `relationship` field, this is the
135
- * foreign-key column name (`<field>Id`), since that's the column Prisma marks
136
- * `@unique`, not the relation field itself.
137
- *
138
- * The config exposes no list-level compound (`@@unique`) declaration, so this
139
- * cannot validate a compound `<Model>_<a>_<b>` selector — `where` must contain
140
- * exactly one recognised single-field unique key and no others. This rejects
141
- * non-unique filters (#567) without ever rejecting a valid single-field unique
142
- * lookup; a compound-unique or otherwise non-unique lookup should use
143
- * `findFirst` instead (see #565).
144
- */
145
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
146
- function getUniqueWhereKeys(listConfig: ListConfig<any>): Set<string> {
147
- const keys = new Set<string>(['id'])
148
-
149
- for (const [fieldKey, fieldConfig] of Object.entries(listConfig.fields)) {
150
- if (!fieldConfig || typeof fieldConfig !== 'object') continue
151
- if (!('isIndexed' in fieldConfig) || fieldConfig.isIndexed !== 'unique') continue
152
-
153
- if (fieldConfig.type === 'relationship') {
154
- // A unique relationship's `@unique` lives on the FK column `<field>Id`.
155
- keys.add(`${fieldKey}Id`)
156
- } else {
157
- keys.add(fieldKey)
158
- }
159
- }
160
-
161
- return keys
162
- }
163
-
164
- /**
165
- * Enforce Keystone `findOne` semantics for `findUnique`: the caller-supplied
166
- * `where` must be a valid unique selector. A non-unique `where` is a caller-shape
167
- * error (not an access denial), so this THROWS rather than silently returning
168
- * `null` — consistent with the fail-loud-on-misuse stance of PRD #581. A
169
- * non-unique single-row lookup should use `findFirst` instead (see #565).
170
- */
171
- function assertUniqueWhere(
172
- where: Record<string, unknown> | undefined,
173
- uniqueKeys: Set<string>,
174
- listName: string,
175
- ): void {
176
- const keys = where ? Object.keys(where) : []
177
-
178
- const message =
179
- `findUnique on "${listName}" requires a unique \`where\` (a single unique key such as ` +
180
- `${Array.from(uniqueKeys).join(', ')}). ` +
181
- `Received: ${keys.length === 0 ? '{}' : `{ ${keys.join(', ')} }`}. ` +
182
- `Use \`findFirst\` for a non-unique single-row lookup.`
183
-
184
- if (keys.length !== 1 || !uniqueKeys.has(keys[0])) {
185
- throw new ValidationError([message], {})
186
- }
187
- }
188
-
189
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
190
- function shouldAutoCreate(listConfig: ListConfig<any>): boolean {
191
- if (!listConfig.isSingleton) return false
192
- if (typeof listConfig.isSingleton === 'boolean') return true
193
- return listConfig.isSingleton.autoCreate !== false
194
- }
195
-
196
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
197
- function getDefaultData(listConfig: ListConfig<any>): Record<string, unknown> {
198
- const data: Record<string, unknown> = {}
199
-
200
- for (const [fieldKey, fieldConfig] of Object.entries(listConfig.fields)) {
201
- if (fieldConfig.virtual) continue
202
-
203
- if (fieldKey === 'id' || fieldKey === 'createdAt' || fieldKey === 'updatedAt') continue
204
-
205
- if ('defaultValue' in fieldConfig && fieldConfig.defaultValue !== undefined) {
206
- data[fieldKey] = fieldConfig.defaultValue
207
- }
208
- }
209
-
210
- return data
211
- }
212
-
213
- // A camelCase field name (e.g. a relationship's `tenantId` foreign key) needs
214
- // its word boundary split before title-casing, or it reads as one run-together
215
- // word ("Tenantid") in a user-facing unique-constraint message.
216
- function humanizeFieldName(fieldName: string): string {
217
- const spaced = fieldName.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
218
- return spaced.charAt(0).toUpperCase() + spaced.slice(1)
219
- }
220
-
221
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
222
- function parsePrismaError(error: unknown, listConfig: ListConfig<any>): Error {
223
- if (
224
- error &&
225
- typeof error === 'object' &&
226
- 'code' in error &&
227
- 'meta' in error &&
228
- typeof error.code === 'string'
229
- ) {
230
- const prismaError = error as { code: string; meta?: { target?: string[] }; message?: string }
231
-
232
- // P2002 is Prisma's unique constraint violation code.
233
- if (prismaError.code === 'P2002') {
234
- const target = uniqueConstraintOf(prismaError)?.fields
235
- const fieldErrors: Record<string, string> = {}
236
-
237
- if (target && target.length > 0) {
238
- for (const fieldName of target) {
239
- const fieldConfig = listConfig.fields[fieldName]
240
-
241
- if (fieldConfig) {
242
- fieldErrors[fieldName] =
243
- `This ${humanizeFieldName(fieldName).toLowerCase()} is already in use`
244
- } else {
245
- fieldErrors[fieldName] = `This value is already in use`
246
- }
247
- }
248
-
249
- const fieldLabels = target.map(humanizeFieldName).join(', ')
250
- return new DatabaseError(
251
- `${fieldLabels} must be unique. The value you entered is already in use.`,
252
- fieldErrors,
253
- prismaError.code,
254
- )
255
- }
256
-
257
- return new DatabaseError('A record with this value already exists', {}, prismaError.code)
258
- }
259
-
260
- return new DatabaseError(
261
- prismaError.message || 'A database error occurred',
262
- {},
263
- prismaError.code,
264
- )
265
- }
266
-
267
- if (error instanceof Error) {
268
- return error
269
- }
270
-
271
- return new Error('An unknown error occurred')
272
- }
273
-
274
- /**
275
- * Mirrors Prisma's `TransactionIsolationLevel`. Provider support varies —
276
- * e.g. `Serializable` requires PostgreSQL.
277
- */
278
- export type TransactionIsolationLevel =
279
- 'ReadUncommitted' | 'ReadCommitted' | 'RepeatableRead' | 'Serializable' | 'Snapshot'
280
-
281
- /**
282
- * Options for {@link StackContext.transaction}, forwarded verbatim to the
283
- * underlying Prisma interactive transaction.
284
- */
285
- export interface TransactionOptions {
286
- /** Max ms to wait to acquire a transaction from the pool. */
287
- maxWait?: number
288
- /** Max ms the interactive transaction may run before timing out. */
289
- timeout?: number
290
- /** Isolation level for the transaction (e.g. `'Serializable'`). */
291
- isolationLevel?: TransactionIsolationLevel
292
- }
293
-
294
- /**
295
- * Minimal shape of a Prisma client that can open an interactive transaction.
296
- * A Prisma transaction client (the `tx` handed to the callback) intentionally
297
- * does NOT expose `$transaction`, which is how nested writes detect they are
298
- * already inside a transaction and join it rather than opening another.
299
- */
300
- interface TransactionCapable<TPrisma> {
301
- $transaction?: (
302
- fn: (tx: TPrisma) => Promise<unknown>,
303
- options?: TransactionOptions,
304
- ) => Promise<unknown>
305
- }
306
-
307
- /**
308
- * The access-controlled context returned by {@link getContext}.
309
- *
310
- * Exposes the secured `db` delegate plus the session, raw `prisma`, storage,
311
- * plugin services, the generic `serverAction` handler, `sudo()` (bypasses access
312
- * control but still runs hooks), `withSession()` (substitutes the session but
313
- * still runs access control), and `transaction()` (interactive, hook-firing
314
- * transaction). All access-checked operations run their list/field hooks.
315
- */
316
- export interface StackContext<
317
- TPrisma extends PrismaClientLike = PrismaClientLike,
318
- // Defaults to the plain Prisma-shaped view (#1232). The generator points a
319
- // list's `TypeInfo['db']` at its own generated `CustomDB` — the same
320
- // virtual/transformed-field-augmented description `context.db` already
321
- // resolves to outside a hook — so a hook's `context: StackContext<TPrisma,
322
- // TDb>` (keyed via `TTypeInfo['db']`) describes the same rows. Left
323
- // unconstrained (no `extends AccessControlledDB<TPrisma>`) — `CustomDB`'s
324
- // per-list payload requires strictly more keys than the raw Prisma payload,
325
- // so constraining this parameter would reintroduce the assignability gap
326
- // #1233 already worked around for the fragment overload, one level higher.
327
- TDb = AccessControlledDB<TPrisma>,
328
- > {
329
- db: TDb
330
- session: Session | null
331
- prisma: TPrisma
332
- storage: StorageUtils
333
- plugins: Record<string, unknown>
334
- serverAction: (props: ServerActionProps) => Promise<unknown>
335
- /**
336
- * Run `fn` inside ONE interactive transaction. The `txContext` handed to `fn`
337
- * is a full {@link StackContext} whose `db.*` operations are access-checked and
338
- * hook-firing (identical to this context) but persist against the transaction
339
- * client, so every write in the callback is atomic — a throw anywhere rolls the
340
- * whole transaction back.
341
- *
342
- * `options` (notably `isolationLevel`) is forwarded to the underlying Prisma
343
- * transaction. Serialization failures (e.g. Prisma `P2034`) propagate to the
344
- * caller rather than being swallowed, so the caller can own a retry loop. If
345
- * the client cannot open an interactive transaction (e.g. a plain mock, or we
346
- * are already inside a transaction), `fn` runs directly against the current
347
- * client with identical hook/access semantics.
348
- *
349
- * Caveat: plugin runtime services (`txContext.plugins`) stay bound to the
350
- * top-level (non-transaction) client — they are shared services initialised
351
- * once per request. Reads through a plugin service therefore won't see this
352
- * transaction's uncommitted writes, and a plugin service that WRITES would
353
- * escape the transaction and survive a rollback. Use `txContext.db` (not a
354
- * plugin service) for writes that must be atomic with the transaction.
355
- */
356
- transaction: <T>(
357
- fn: (txContext: StackContext<TPrisma, TDb>) => Promise<T>,
358
- options?: TransactionOptions,
359
- ) => Promise<T>
360
- sudo: () => StackContext<TPrisma, TDb>
361
- /**
362
- * Derive a context identical to this one except for its session, reusing
363
- * the already-resolved config and this context's own client (including a
364
- * transaction client — a call inside `context.transaction()` stays in that
365
- * transaction) and storage.
366
- *
367
- * **This is not an authorisation.** It substitutes who hooks and access
368
- * control see; it does not change what they decide. The derived context
369
- * can do exactly what any context built with `session` directly could
370
- * do — access rules still evaluate against the new session. The caller is
371
- * responsible for deciding who may invoke this.
372
- *
373
- * Orthogonal to `sudo()`: `withSession(s)` preserves the receiver's sudo
374
- * state (elevated stays elevated), so `context.withSession(s).sudo()` and
375
- * `context.sudo().withSession(s)` are equivalent.
376
- */
377
- withSession: (session: Session | null) => StackContext<TPrisma, TDb>
378
- _isSudo: boolean
379
- /**
380
- * @internal Present so a hook-bound `StackContext` (issue #1176) satisfies
381
- * {@link AccessContext} and can be threaded through the same internal
382
- * write-pipeline/access plumbing that a plain `AccessContext` is — see
383
- * `_resolveOutputChain` on `AccessContext` for what this tracks.
384
- */
385
- _resolveOutputChain: readonly { listKey: string; fieldKey: string }[]
386
- /** @internal See `_transactionOwner` on `AccessContext`. */
387
- _transactionOwner?: TransactionRegistry
388
- }
389
-
390
- /**
391
- * Drain a `context.transaction()` owner's deferral registry once its callback
392
- * (and any real underlying transaction) has settled (ADR-0028). A transaction/
393
- * callback error always wins — compensators still all run, but their errors
394
- * are discarded in favor of re-surfacing the original, matching the Write
395
- * Pipeline's `txError` precedence — otherwise any deferred `afterTransaction`
396
- * errors reject with {@link AfterTransactionError} even though the callback
397
- * succeeded and the transaction committed.
398
- */
399
- async function settleTransactionOwner<T>(
400
- settled: Promise<T>,
401
- registry: TransactionRegistry,
402
- ): Promise<T> {
403
- const errors: unknown[] = []
404
- let result: T
405
- try {
406
- result = await settled
407
- } catch (err) {
408
- const outcome: TransactionSettleOutcome = { status: 'rolled-back', error: err }
409
- await registry.drain(outcome, errors)
410
- throw err
411
- }
412
- await registry.drain({ status: 'committed' }, errors)
413
- if (errors.length > 0) {
414
- throw new AfterTransactionError(errors)
415
- }
416
- return result
417
- }
418
-
419
- export function getContext<
420
- TConfig extends OpenSaasConfig,
421
- TPrisma extends PrismaClientLike = PrismaClientLike,
422
- // See the identical `TDb` doc on `StackContext` (#1232) — left unconstrained
423
- // for the same reason. Defaults to the plain access-controlled view so every
424
- // existing two-argument call site is unaffected; a caller that wants the
425
- // generated `Context`'s `db` description asks for it explicitly:
426
- // `getContext<typeof config, PrismaClient, CustomDB>(...)`. This is the type
427
- // parameter that lets the generated context factory return a `StackContext`
428
- // already shaped as `CustomDB` instead of `as unknown as`-ing its way there
429
- // (#1328).
430
- TDb = AccessControlledDB<TPrisma>,
431
- >(
432
- config: TConfig,
433
- prisma: TPrisma,
434
- session: Session | null,
435
- storage?: StorageUtils,
436
- _isSudo: boolean = false,
437
- // Internal: when rebuilding the context against a transaction client, reuse the
438
- // already-initialised plugin services rather than re-running plugin runtimes.
439
- _sharedPlugins?: Record<string, unknown>,
440
- // Internal (ADR-0028, #899): when rebuilding the context for a transaction
441
- // owner's callback body, carry the deferral registry so writes reached
442
- // through this context join it instead of firing afterTransaction eagerly.
443
- _transactionOwner?: TransactionRegistry,
444
- // Internal (ADR-0023, issue #1176): when rebuilding the context for a
445
- // hook-bound write (or a derived `sudo()`/`withSession()` of one), carry the
446
- // resolve chain forward so a write issued from inside a `resolveOutput` hook
447
- // keeps that hook's cycle-guard chain instead of resetting to empty.
448
- _resolveOutputChain?: readonly { listKey: string; fieldKey: string }[],
449
- ): StackContext<TPrisma, TDb> {
450
- // Broad type to allow dynamic model access; populated by populateDbDelegate below.
451
- const db: Record<string, unknown> = {}
452
-
453
- const context: AccessContext<TPrisma> = {
454
- session,
455
- prisma: prisma as TPrisma,
456
- db: db as AccessControlledDB<TPrisma>,
457
- storage: storage ?? {
458
- uploadFile: async () => {
459
- throw new Error(
460
- 'No storage providers configured. Add storage providers to your opensaas.config.ts',
461
- )
462
- },
463
- uploadImage: async () => {
464
- throw new Error(
465
- 'No storage providers configured. Add storage providers to your opensaas.config.ts',
466
- )
467
- },
468
- deleteFile: async () => {
469
- throw new Error(
470
- 'No storage providers configured. Add storage providers to your opensaas.config.ts',
471
- )
472
- },
473
- deleteImage: async () => {
474
- throw new Error(
475
- 'No storage providers configured. Add storage providers to your opensaas.config.ts',
476
- )
477
- },
478
- },
479
- // Reuse already-initialised plugin services when rebinding to a transaction
480
- // client, otherwise start empty and populate via plugin runtimes below.
481
- plugins: _sharedPlugins ?? {},
482
- _isSudo,
483
- _resolveOutputChain: _resolveOutputChain ?? [],
484
- _transactionOwner,
485
- }
486
-
487
- populateDbDelegate(db, config, prisma, context)
488
-
489
- // Skipped when reusing shared plugins (transaction rebind) so runtimes — and
490
- // any side effects they carry — run exactly once per top-level context.
491
- if (!_sharedPlugins) {
492
- const pluginsToExecute = config._plugins || config.plugins || []
493
- for (const plugin of pluginsToExecute) {
494
- if (plugin.runtime) {
495
- try {
496
- // Passed as a plain second argument rather than a method on
497
- // `context` itself — see the `sudo` param doc on `Plugin['runtime']`.
498
- context.plugins[plugin.name] = plugin.runtime(
499
- context,
500
- () => sudo() as unknown as AccessContext<TPrisma>,
501
- )
502
- } catch (error) {
503
- console.error(`Error executing runtime for plugin "${plugin.name}":`, error)
504
- }
505
- }
506
- }
507
- }
508
-
509
- // Returns a result object instead of throwing — required for server actions
510
- // to work in Next.js production builds.
511
- async function serverAction(props: ServerActionProps): Promise<
512
- | { success: true; data: unknown }
513
- | { success: false; error: string; fieldErrors?: Record<string, string> }
514
- // The distinct shapes below (never `success`) mirror the ServerActionProps
515
- // variants above — see their comments for the redirect-on-`success`
516
- // footgun each one avoids.
517
- | { deleted: number; total: number }
518
- | { removed: boolean; error?: string }
519
- | { created: boolean; id?: string; error?: string; fieldErrors?: Record<string, string> }
520
- | { bulkAction: true; message?: string }
521
- | { bulkAction: false; error: string }
522
- | { updated: boolean; error?: string; fieldErrors?: Record<string, string> }
523
- > {
524
- const dbKey = getDbKey(props.listKey)
525
- const listConfig = config.lists[props.listKey]
526
-
527
- if (!listConfig) {
528
- return {
529
- success: false,
530
- error: `List "${props.listKey}" not found in configuration`,
531
- }
532
- }
533
-
534
- const model = db[dbKey] as {
535
- create: (args: { data: Record<string, unknown> }) => Promise<unknown>
536
- update: (args: { where: { id: string }; data: Record<string, unknown> }) => Promise<unknown>
537
- delete: (args: { where: { id: string } }) => Promise<unknown>
538
- }
539
-
540
- // Bulk delete: remove each id row-by-row through the secured context,
541
- // honouring Silent failure — a denied (or missing) row returns `null` and is
542
- // simply not counted. Returns "N of M" so partial denials are visible without
543
- // revealing which rows were denied or why. One row's error never aborts the
544
- // rest.
545
- if (props.action === 'bulkDelete') {
546
- let deleted = 0
547
- for (const id of props.ids) {
548
- try {
549
- const result = await model.delete({ where: { id } })
550
- if (result !== null && result !== undefined) deleted++
551
- } catch {
552
- // Skip this row (e.g. a DB constraint error); it is not counted.
553
- }
554
- }
555
- return { deleted, total: props.ids.length }
556
- }
557
-
558
- // Custom Bulk action (issue #736). Look the declared action up by `key` and
559
- // run its server-side `handler` over the selected ids with THIS secured
560
- // context — the handler does its own row-by-row work through `context.db`,
561
- // so per-id access control and hooks apply and denials stay Silent. The
562
- // `hasAccess` visibility gate (if any) is re-checked here so a hidden action
563
- // can never be invoked by a hand-crafted request; the client only ever sends
564
- // the serialisable `{ key, ids }`, never the handler itself.
565
- if (props.action === 'bulkAction') {
566
- const bulkActions = listConfig.ui?.listView?.bulkActions ?? []
567
- const action = bulkActions.find((a) => a.key === props.key)
568
- if (!action) {
569
- return {
570
- bulkAction: false,
571
- error: `Bulk action "${props.key}" not found on list "${props.listKey}"`,
572
- }
573
- }
574
- if (action.hasAccess) {
575
- const allowed = await action.hasAccess({
576
- session: context.session,
577
- context,
578
- listKey: props.listKey,
579
- })
580
- if (!allowed) {
581
- return { bulkAction: false, error: 'Access denied' }
582
- }
583
- }
584
- try {
585
- const result = await action.handler({
586
- listKey: props.listKey,
587
- ids: props.ids,
588
- context,
589
- })
590
- return { bulkAction: true, message: result?.message }
591
- } catch (error) {
592
- if (error instanceof ValidationError || error instanceof DatabaseError) {
593
- return { bulkAction: false, error: error.message }
594
- }
595
- const dbError = parsePrismaError(error, listConfig)
596
- // A recognised Prisma error carries a user-safe, translated message.
597
- if (dbError instanceof DatabaseError) {
598
- return { bulkAction: false, error: dbError.message }
599
- }
600
- // Anything else is an unexpected handler bug whose raw `.message` could
601
- // leak internal detail to the client — log it server-side and return a
602
- // generic client-facing message instead.
603
- console.error(`Bulk action "${props.key}" on list "${props.listKey}" failed:`, error)
604
- return { bulkAction: false, error: 'Action failed' }
605
- }
606
- }
607
-
608
- // Runs on the RELATED row (ADR-0018 boundary — see ServerActionProps above).
609
- // Honours Silent failure: an access-denied operation returns `null`, which
610
- // becomes `{ removed: false }` with a generic reason — never leaking whether
611
- // the row was denied or absent.
612
- if (props.action === 'removeRelated') {
613
- try {
614
- let result: unknown = null
615
- if (props.mode === 'delete') {
616
- result = await model.delete({ where: { id: props.id } })
617
- } else {
618
- // Disconnect: an UPDATE on the related list nulling its back-reference,
619
- // never a delete — the row itself survives. A to-one back-reference
620
- // disconnects with `true`; a to-many back-reference (many-to-many)
621
- // disconnects the specific parent by id.
622
- if (!props.field) {
623
- return { removed: false, error: 'Missing back-reference field for disconnect' }
624
- }
625
- const backRefField = listConfig.fields[props.field]
626
- const backRefIsMany =
627
- !!backRefField && 'many' in backRefField && backRefField.many === true
628
- const disconnectValue = backRefIsMany
629
- ? { disconnect: { id: props.parentId } }
630
- : { disconnect: true }
631
- result = await model.update({
632
- where: { id: props.id },
633
- data: { [props.field]: disconnectValue },
634
- })
635
- }
636
- if (result === null || result === undefined) {
637
- return { removed: false, error: 'Access denied or operation failed' }
638
- }
639
- return { removed: true }
640
- } catch (error) {
641
- if (error instanceof ValidationError || error instanceof DatabaseError) {
642
- return { removed: false, error: error.message }
643
- }
644
- const dbError = parsePrismaError(error, listConfig)
645
- return { removed: false, error: dbError.message }
646
- }
647
- }
648
-
649
- // Runs on the RELATED list (ADR-0018 boundary — see ServerActionProps above).
650
- // The back-reference to the parent is set here from `field`/`parentId` (a
651
- // to-one back-ref connects a single parent; a to-many back-ref, e.g.
652
- // many-to-many, connects the parent by id), so the client can never
653
- // re-target the link. Honours Silent failure: an access-denied create
654
- // returns `null`, surfaced as `{ created: false }` with a generic reason
655
- // (no denied-vs-absent leak).
656
- if (props.action === 'createRelated') {
657
- try {
658
- // Defensive guard (hardening; unreachable from the drawer, which always
659
- // mounts on a valid back-reference and sends BOTH field and parentId).
660
- // A lone field/parentId is a malformed direct call — reject it rather
661
- // than silently skip back-reference injection and let a client-supplied
662
- // data[field] slip through unguarded to the create.
663
- if (!!props.field !== !!props.parentId) {
664
- return {
665
- created: false,
666
- error: 'createRelated requires both field and parentId, or neither',
667
- }
668
- }
669
- const data: Record<string, unknown> = { ...props.data }
670
- if (props.field && props.parentId) {
671
- const backRefField = listConfig.fields[props.field]
672
- // The back-reference must name a relationship field on this list; a
673
- // non-relationship field would otherwise receive a nonsensical
674
- // { connect } value. Also hardening — the drawer only ever passes a
675
- // real relationship back-reference here.
676
- if (!backRefField || backRefField.type !== 'relationship') {
677
- return {
678
- created: false,
679
- error: `Field "${props.field}" on list "${props.listKey}" is not a relationship field`,
680
- }
681
- }
682
- const backRefIsMany = 'many' in backRefField && backRefField.many === true
683
- // The back-reference is set on the SERVER from the trusted parentId,
684
- // OVERWRITING any client-supplied data[field] spread in above, so a
685
- // hostile client can never re-target the link (a to-many back-ref
686
- // connects the parent by id).
687
- data[props.field] = backRefIsMany
688
- ? { connect: [{ id: props.parentId }] }
689
- : { connect: { id: props.parentId } }
690
- }
691
- const result = await model.create({ data })
692
- if (result === null || result === undefined) {
693
- return { created: false, error: 'Access denied or operation failed' }
694
- }
695
- const id =
696
- typeof result === 'object' && result !== null && 'id' in result
697
- ? String((result as { id: unknown }).id)
698
- : undefined
699
- return { created: true, id }
700
- } catch (error) {
701
- if (error instanceof ValidationError || error instanceof DatabaseError) {
702
- return { created: false, error: error.message, fieldErrors: error.fieldErrors }
703
- }
704
- const dbError = parsePrismaError(error, listConfig)
705
- return {
706
- created: false,
707
- error: dbError.message,
708
- fieldErrors: dbError instanceof DatabaseError ? dbError.fieldErrors : undefined,
709
- }
710
- }
711
- }
712
-
713
- // Updates ONE scalar field on the RELATED row (ADR-0018 boundary — see
714
- // ServerActionProps above). Honours Silent failure: an access-denied update
715
- // returns `null`, surfaced as `{ updated: false }` with a generic reason (no
716
- // denied-vs-absent leak); a validation/db error surfaces its message and
717
- // fieldErrors so the cell can revert with a reason and show an inline error.
718
- if (props.action === 'updateRelated') {
719
- try {
720
- const result = await model.update({
721
- where: { id: props.id },
722
- data: { [props.field]: props.value },
723
- })
724
- if (result === null || result === undefined) {
725
- return { updated: false, error: 'Access denied or operation failed' }
726
- }
727
- return { updated: true }
728
- } catch (error) {
729
- if (error instanceof ValidationError || error instanceof DatabaseError) {
730
- return { updated: false, error: error.message, fieldErrors: error.fieldErrors }
731
- }
732
- const dbError = parsePrismaError(error, listConfig)
733
- return {
734
- updated: false,
735
- error: dbError.message,
736
- fieldErrors: dbError instanceof DatabaseError ? dbError.fieldErrors : undefined,
737
- }
738
- }
739
- }
740
-
741
- try {
742
- if (props.action === 'relationshipOptions') {
743
- const fieldConfig = listConfig.fields[props.field] as
744
- { type?: string; ref?: string } | undefined
745
- if (!fieldConfig || fieldConfig.type !== 'relationship' || !fieldConfig.ref) {
746
- return {
747
- success: false,
748
- error: `Field "${props.field}" on list "${props.listKey}" is not a relationship field`,
749
- }
750
- }
751
-
752
- const relatedListKey = fieldConfig.ref.split('.')[0]
753
- const options = await getRelationshipOptions(context, config, relatedListKey, {
754
- search: props.search,
755
- take: props.take,
756
- selectedIds: props.selectedIds,
757
- })
758
-
759
- return { success: true, data: options }
760
- }
761
-
762
- let result: unknown = null
763
-
764
- if (props.action === 'create') {
765
- result = await model.create({ data: props.data })
766
- } else if (props.action === 'update') {
767
- result = await model.update({
768
- where: { id: props.id },
769
- data: props.data,
770
- })
771
- } else if (props.action === 'delete') {
772
- result = await model.delete({
773
- where: { id: props.id },
774
- })
775
- }
776
-
777
- // Check for access denial (null return from access-controlled operations)
778
- if (result === null) {
779
- return {
780
- success: false,
781
- error: 'Access denied or operation failed',
782
- }
783
- }
784
-
785
- return {
786
- success: true,
787
- data: result,
788
- }
789
- } catch (error) {
790
- if (error instanceof ValidationError) {
791
- return {
792
- success: false,
793
- error: error.message,
794
- fieldErrors: error.fieldErrors,
795
- }
796
- }
797
-
798
- if (error instanceof DatabaseError) {
799
- return {
800
- success: false,
801
- error: error.message,
802
- fieldErrors: error.fieldErrors,
803
- }
804
- }
805
-
806
- const dbError = parsePrismaError(error, listConfig)
807
- if (dbError instanceof DatabaseError) {
808
- return {
809
- success: false,
810
- error: dbError.message,
811
- fieldErrors: dbError.fieldErrors,
812
- }
813
- }
814
-
815
- return {
816
- success: false,
817
- error: dbError.message,
818
- }
819
- }
820
- }
821
-
822
- // Bypasses access control; hooks and validation still run.
823
- function sudo(): StackContext<TPrisma, TDb> {
824
- return getContext<TConfig, TPrisma, TDb>(
825
- config,
826
- prisma,
827
- session,
828
- context.storage,
829
- true,
830
- undefined,
831
- // ADR-0028: a sudo write issued from inside an owned transaction (e.g.
832
- // `tx.sudo().db.x.create()`) must still defer to that owner.
833
- context._transactionOwner,
834
- // #1176: carry the resolve chain forward so a `context.sudo()` called
835
- // from inside a `resolveOutput` hook keeps that hook's cycle-guard
836
- // chain (ADR-0023) rather than resetting to empty.
837
- context._resolveOutputChain,
838
- )
839
- }
840
-
841
- // Substitutes the session; access control and hooks still run against it
842
- // (orthogonal to `sudo`, so the receiver's sudo state is preserved).
843
- function withSession(newSession: Session | null): StackContext<TPrisma, TDb> {
844
- return getContext<TConfig, TPrisma, TDb>(
845
- config,
846
- prisma,
847
- newSession,
848
- context.storage,
849
- _isSudo,
850
- undefined,
851
- // ADR-0028: a write issued from inside an owned transaction (e.g.
852
- // `tx.withSession(s).db.x.create()`) must still defer to that owner.
853
- context._transactionOwner,
854
- // #1176: see the identical comment in `sudo()` above.
855
- context._resolveOutputChain,
856
- )
857
- }
858
-
859
- // Interactive, hook-firing transaction (#614). See the `transaction` doc on
860
- // `StackContext` above for the atomicity/isolation/retry contract.
861
- //
862
- // This call OWNS a deferral registry for its callback's writes (ADR-0028):
863
- // it always observes when its own callback settles — resolve/reject — even
864
- // when the underlying client cannot open a real interactive transaction, so
865
- // every `txContext.db.*` write defers its transaction-boundary bracket here
866
- // instead of firing eagerly, and this call flushes them with the real
867
- // outcome once the callback (and any real transaction) has settled. A
868
- // `transaction()` nested inside another joins the outer owner's queue
869
- // rather than creating a second one.
870
- function transaction<T>(
871
- fn: (txContext: StackContext<TPrisma, TDb>) => Promise<T>,
872
- options?: TransactionOptions,
873
- ): Promise<T> {
874
- if (context._transactionOwner) {
875
- return fn(returned)
876
- }
877
-
878
- const registry = new TransactionRegistry()
879
- const client = prisma as unknown as TransactionCapable<TPrisma>
880
-
881
- const settled =
882
- typeof client.$transaction !== 'function'
883
- ? // No interactive transaction available (plain client/mock, or already
884
- // inside one — see `TransactionCapable` above). Run directly: hook/
885
- // access semantics are identical, atomicity comes from the enclosing
886
- // transaction.
887
- fn(
888
- getContext<TConfig, TPrisma, TDb>(
889
- config,
890
- prisma,
891
- session,
892
- context.storage,
893
- _isSudo,
894
- context.plugins,
895
- registry,
896
- context._resolveOutputChain,
897
- ),
898
- )
899
- : (client.$transaction(
900
- (tx) =>
901
- fn(
902
- getContext<TConfig, TPrisma, TDb>(
903
- config,
904
- tx,
905
- session,
906
- context.storage,
907
- _isSudo,
908
- context.plugins,
909
- registry,
910
- context._resolveOutputChain,
911
- ),
912
- ),
913
- options,
914
- ) as Promise<T>)
915
-
916
- return settleTransactionOwner(settled, registry)
917
- }
918
-
919
- const returned: StackContext<TPrisma, TDb> = {
920
- // The one place that legitimately knows `db` is shaped as the caller's
921
- // `TDb` says: `populateDbDelegate` above always builds the plain
922
- // `AccessControlledDB<TPrisma>` runtime shape, and a caller asking for a
923
- // richer description (e.g. the generated `CustomDB`) is asserting that
924
- // description is compatible with what actually comes back at runtime.
925
- // This is the single internal cast `TDb` exists to replace every
926
- // consumer-side `as unknown as` with (#1328).
927
- db: db as unknown as TDb,
928
- session,
929
- prisma,
930
- storage: context.storage,
931
- plugins: context.plugins,
932
- serverAction,
933
- sudo,
934
- withSession,
935
- transaction,
936
- _isSudo,
937
- // #1176: carried so a `StackContext` structurally satisfies `AccessContext`
938
- // and can be handed, unchanged, to the internal write-pipeline/hook
939
- // plumbing that a plain `AccessContext` was built for — see
940
- // `bindContextToTransaction` in `write-pipeline.ts`.
941
- _resolveOutputChain: context._resolveOutputChain,
942
- _transactionOwner: context._transactionOwner,
943
- }
944
- return returned
945
- }
946
-
947
- /**
948
- * Populate `target` with the access-controlled CRUD operations for every list,
949
- * each bound to `prisma` and `context`. Used both by {@link getContext} (at
950
- * request setup) and by the Write Pipeline to rebuild a `db` delegate against a
951
- * transaction client (ADR-0010), so a hook's `context.db` write participates in
952
- * the same transaction.
953
- *
954
- * The operations capture `prisma` at construction, so rebinding to a different
955
- * client (e.g. a transaction `tx`) requires rebuilding the delegate — which is
956
- * exactly what this function enables.
957
- */
958
- export function populateDbDelegate<TPrisma extends PrismaClientLike>(
959
- target: Record<string, unknown>,
960
- config: OpenSaasConfig,
961
- prisma: TPrisma,
962
- context: AccessContext<TPrisma>,
963
- ): void {
964
- for (const [listName, listConfig] of Object.entries(config.lists)) {
965
- const dbKey = getDbKey(listName)
966
-
967
- const createOp = createCreate(listName, listConfig, prisma, context, config)
968
- const findManyOp = createFindMany(listName, listConfig, prisma, context, config)
969
- const updateOp = createUpdate(listName, listConfig, prisma, context, config)
970
- const operations: Record<string, unknown> = {
971
- findUnique: createFindUnique(listName, listConfig, prisma, context, config),
972
- findMany: findManyOp,
973
- findFirst: createFindFirst(findManyOp),
974
- create: createOp,
975
- update: updateOp,
976
- delete: createDelete(listName, listConfig, prisma, context, config),
977
- count: createCount(listName, listConfig, prisma, context, config),
978
- createMany: createCreateMany(listName, listConfig, prisma, context, config, createOp),
979
- updateMany: createUpdateMany(
980
- listName,
981
- listConfig,
982
- prisma,
983
- context,
984
- config,
985
- findManyOp,
986
- updateOp,
987
- ),
988
- }
989
-
990
- if (isSingletonList(listConfig)) {
991
- operations.get = createGet(listName, listConfig, prisma, context, config, createOp)
992
- }
993
-
994
- target[dbKey] = operations
995
- }
996
- }
997
-
998
- /**
999
- * Build a fresh access-controlled `db` delegate bound to `prisma` and `context`.
1000
- * Convenience wrapper over {@link populateDbDelegate} returning a new object,
1001
- * used by the Write Pipeline to rebind `db` to a transaction client.
1002
- */
1003
- export function buildDbDelegate<TPrisma extends PrismaClientLike>(
1004
- config: OpenSaasConfig,
1005
- prisma: TPrisma,
1006
- context: AccessContext<TPrisma>,
1007
- ): AccessControlledDB<TPrisma> {
1008
- const db: Record<string, unknown> = {}
1009
- populateDbDelegate(db, config, prisma, context)
1010
- return db as AccessControlledDB<TPrisma>
1011
- }
1012
-
1013
- /**
1014
- * Resolve the `include` (and declared-dependency provenance) a read should
1015
- * use, preserving each existing path's exact shape — fragment / sudo /
1016
- * caller include / bare (ADR-0024) — while folding declared dependencies
1017
- * (`needs`, ADR-0025) into whichever of those the read is already using.
1018
- *
1019
- * A non-sudo fragment's own `include` and a non-sudo caller's `include` are
1020
- * both folded and then scoped by `buildAccessScopedInclude` (ADR-0026) —
1021
- * caller-directed, so a relation named nowhere in the folded tree never has
1022
- * its list's `query` access evaluated at all (issue #1088: a fragment read
1023
- * used to skip this walk entirely). A sudo caller's `include` (fragment or
1024
- * not) is folded and used as-is, unscoped — sudo is unaffected. A bare read
1025
- * stays on the exact ADR-0024 path — `include: undefined`, no related
1026
- * `query` access evaluated — unless folding actually added something, which
1027
- * only happens when a field on this list declares `needs`.
1028
- *
1029
- * Also returns the `FieldSelectionScope` a fragment's own field selection
1030
- * produces (ADR-0027), so the caller can pass it to `filterReadableFields`
1031
- * and make computation itself projection-aware, not only the fold above.
1032
- * `undefined` for every non-fragment path: a caller `include` (sudo or not)
1033
- * and a bare read both mean "compute every field," matching what they
1034
- * already fetch.
1035
- *
1036
- * Also returns `toOneAccessFilters` — the to-one relations `buildAccessScopedInclude`
1037
- * flagged as needing a post-query existence check rather than a Prisma-side
1038
- * `where` (issue #974). Only a non-sudo fragment or caller-include read can
1039
- * produce a non-empty tree: those are the only paths that evaluate a related
1040
- * list's `query` access at all. A sudo read and a bare read always return an
1041
- * empty tree.
1042
- */
1043
- async function resolveReadInclude(
1044
- callerInclude: Record<string, unknown> | undefined,
1045
- fragmentFields: FieldSelection<unknown> | undefined,
1046
- listName: string,
1047
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1048
- listConfig: ListConfig<any>,
1049
- context: AccessContext & { _isSudo?: boolean },
1050
- config: OpenSaasConfig,
1051
- ): Promise<{
1052
- include: Record<string, unknown> | undefined
1053
- declaredOnly: DeclaredOnlyTree
1054
- selection: FieldSelectionScope | undefined
1055
- toOneAccessFilters: ToOneAccessFilterTree
1056
- countDenials: CountAccessDenialTree
1057
- }> {
1058
- if (fragmentFields !== undefined) {
1059
- const fragmentInclude = buildInclude(fragmentFields) ?? undefined
1060
- const selection = buildFieldSelectionScope(fragmentFields)
1061
- const folded = foldDeclaredDependencies(
1062
- fragmentInclude,
1063
- listConfig.fields,
1064
- config,
1065
- listName,
1066
- [listName],
1067
- selection,
1068
- )
1069
-
1070
- if (context._isSudo || !folded.include) {
1071
- return {
1072
- ...folded,
1073
- selection,
1074
- toOneAccessFilters: emptyToOneAccessFilterTree(),
1075
- countDenials: emptyCountAccessDenialTree(),
1076
- }
1077
- }
1078
-
1079
- const { include, toOneAccessFilters, countDenials } = await buildAccessScopedInclude(
1080
- folded.include,
1081
- listConfig.fields,
1082
- { session: context.session, context },
1083
- config,
1084
- listName,
1085
- )
1086
- return {
1087
- include,
1088
- declaredOnly: folded.declaredOnly,
1089
- selection,
1090
- toOneAccessFilters,
1091
- countDenials,
1092
- }
1093
- }
1094
-
1095
- if (context._isSudo) {
1096
- const folded = foldDeclaredDependencies(callerInclude, listConfig.fields, config, listName)
1097
- return {
1098
- ...folded,
1099
- selection: undefined,
1100
- toOneAccessFilters: emptyToOneAccessFilterTree(),
1101
- countDenials: emptyCountAccessDenialTree(),
1102
- }
1103
- }
1104
-
1105
- const folded = foldDeclaredDependencies(callerInclude, listConfig.fields, config, listName)
1106
- if (!folded.include) {
1107
- return {
1108
- ...folded,
1109
- selection: undefined,
1110
- toOneAccessFilters: emptyToOneAccessFilterTree(),
1111
- countDenials: emptyCountAccessDenialTree(),
1112
- }
1113
- }
1114
-
1115
- const { include, toOneAccessFilters, countDenials } = await buildAccessScopedInclude(
1116
- folded.include,
1117
- listConfig.fields,
1118
- { session: context.session, context },
1119
- config,
1120
- listName,
1121
- )
1122
- return {
1123
- include,
1124
- declaredOnly: folded.declaredOnly,
1125
- selection: undefined,
1126
- toOneAccessFilters,
1127
- countDenials,
1128
- }
1129
- }
1130
-
1131
- function createFindUnique<TPrisma extends PrismaClientLike>(
1132
- listName: string,
1133
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1134
- listConfig: ListConfig<any>,
1135
- prisma: TPrisma,
1136
- context: AccessContext<TPrisma>,
1137
- config: OpenSaasConfig,
1138
- ) {
1139
- return async (args: {
1140
- // Accepts any unique selector at the delegate level (the generated
1141
- // `<List>FindUniqueArgs` type narrows `where` to Prisma's `WhereUniqueInput`).
1142
- // The runtime guard below rejects non-unique shapes.
1143
- where: Record<string, unknown>
1144
- include?: Record<string, unknown>
1145
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1146
- query?: any
1147
- // `select` is not honoured — accepted only so the no-op can be made visible.
1148
- select?: Record<string, unknown>
1149
- }) => {
1150
- warnIfSelectIgnored(args, listName, 'findUnique')
1151
-
1152
- // Runs first, before the access check below — a non-unique `where` is a
1153
- // caller-shape error (see `assertUniqueWhere`), not an access denial. The
1154
- // generated `<List>FindUniqueArgs` only Omits `select`/`include` from
1155
- // Prisma's own type, so `where` stays `<List>WhereUniqueInput` — this
1156
- // runtime guard backstops untyped callers.
1157
- assertUniqueWhere(args.where, getUniqueWhereKeys(listConfig), listName)
1158
-
1159
- let where: Record<string, unknown> = args.where
1160
- if (!context._isSudo) {
1161
- const queryAccess = listConfig.access?.operation?.query
1162
- const accessResult = await checkAccess(queryAccess, {
1163
- session: context.session,
1164
- context,
1165
- })
1166
-
1167
- if (accessResult === false) {
1168
- return null
1169
- }
1170
-
1171
- const mergedWhere = mergeFilters(args.where, accessResult)
1172
- if (mergedWhere === null) {
1173
- return null
1174
- }
1175
- where = mergedWhere
1176
- }
1177
-
1178
- // Access control still runs via filterReadableFields even though a
1179
- // fragment drives `include`; the fragment only narrows which fields come back.
1180
- const fragment = isFragment(args.query) ? args.query : null
1181
-
1182
- // Resolve `include`, folding any declared dependencies (`needs`,
1183
- // ADR-0025) in alongside whatever the fragment/caller/sudo/bare path
1184
- // already produces — see `resolveReadInclude`'s doc comment.
1185
- let { include, declaredOnly, selection, toOneAccessFilters, countDenials } =
1186
- await resolveReadInclude(
1187
- args.include,
1188
- fragment ? fragment._fields : undefined,
1189
- listName,
1190
- listConfig,
1191
- context,
1192
- config,
1193
- )
1194
-
1195
- // Virtual fields have no database column. Whichever path produced
1196
- // `include` (fragment, access-controlled merge, or sudo passthrough), a
1197
- // virtual key must never reach Prisma — it would throw "Unknown field"
1198
- // (#628). Below, `filterReadableFields` computes a virtual field's value
1199
- // exactly when `selection` says the read is going to return it (ADR-0027)
1200
- // — every one of them for a bare/`include`-based read (`selection` is
1201
- // `undefined`), only the ones a fragment named otherwise.
1202
- include = stripVirtualFieldsFromInclude(include, listConfig.fields, config)
1203
-
1204
- // Access Prisma model dynamically - required because model names are generated at runtime
1205
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1206
- const model = (prisma as any)[getDbKey(listName)]
1207
- const item = await model.findFirst({
1208
- where,
1209
- include,
1210
- })
1211
-
1212
- if (!item) {
1213
- return null
1214
- }
1215
-
1216
- // Resolve which of the to-one relations flagged by `toOneAccessFilters`
1217
- // actually survive their related list's `query` access (issue #974) —
1218
- // one batched existence check per relation, before field visibility runs.
1219
- const toOneVisibility = await resolveToOneAccessVisibility([item], toOneAccessFilters, {
1220
- session: context.session,
1221
- context,
1222
- })
1223
-
1224
- // Pass sudo flag through context to skip field-level access checks
1225
- const filtered = await filterReadableFields(
1226
- item,
1227
- listConfig.fields,
1228
- {
1229
- session: context.session,
1230
- context: { ...context, _isSudo: context._isSudo },
1231
- },
1232
- config,
1233
- 0,
1234
- listName,
1235
- declaredOnly,
1236
- selection,
1237
- toOneVisibility,
1238
- countDenials,
1239
- )
1240
-
1241
- if (fragment) {
1242
- return pickFields(filtered, fragment._fields)
1243
- }
1244
-
1245
- return filtered
1246
- }
1247
- }
1248
-
1249
- function createFindMany<TPrisma extends PrismaClientLike>(
1250
- listName: string,
1251
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1252
- listConfig: ListConfig<any>,
1253
- prisma: TPrisma,
1254
- context: AccessContext<TPrisma>,
1255
- config: OpenSaasConfig,
1256
- ) {
1257
- return async (args?: {
1258
- where?: Record<string, unknown>
1259
- orderBy?: Record<string, 'asc' | 'desc'> | Array<Record<string, 'asc' | 'desc'>>
1260
- take?: number
1261
- skip?: number
1262
- include?: Record<string, unknown>
1263
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1264
- query?: any
1265
- // `select` is not honoured — accepted only so the no-op can be made visible.
1266
- select?: Record<string, unknown>
1267
- }) => {
1268
- warnIfSelectIgnored(args, listName, 'findMany')
1269
-
1270
- // Singleton misuse throws rather than silently returning `[]` — unlike an
1271
- // access denial, this is a caller-shape error.
1272
- if (isSingletonList(listConfig)) {
1273
- throw new ValidationError(
1274
- [`Cannot use findMany: ${listName} is a singleton list. Use get() instead.`],
1275
- {},
1276
- )
1277
- }
1278
-
1279
- // Check query access first (skip if sudo mode) — this MUST run before the
1280
- // #912/#915 where/orderBy validation below. See the comment there for why.
1281
- let where: Record<string, unknown> | undefined = args?.where
1282
- if (!context._isSudo) {
1283
- const queryAccess = listConfig.access?.operation?.query
1284
- const accessResult = await checkAccess(queryAccess, {
1285
- session: context.session,
1286
- context,
1287
- })
1288
-
1289
- if (accessResult === false) {
1290
- return []
1291
- }
1292
-
1293
- // #912 — reject a `where`/`orderBy` key the list config doesn't declare
1294
- // (e.g. a Prisma-generated back-relation), and #915 — reject one naming
1295
- // a field this session cannot READ (closing a probe via a `count()`
1296
- // that varies with the withheld value, or an `orderBy` that leaks
1297
- // relative ordering). Both run only now that the caller is known to
1298
- // have SOME access to the list (`accessResult !== false`): the thrown
1299
- // errors name the offending key, and running them before the access
1300
- // check above would let a caller with ZERO access to the list learn a
1301
- // field's name and read-gating status from the error message alone —
1302
- // turning the validation itself into the kind of oracle #915 closes.
1303
- // `sudo` bypasses this whole branch, matching the write path.
1304
- validateQueryKeys({
1305
- where: args?.where,
1306
- orderBy: args?.orderBy,
1307
- listConfig,
1308
- listName,
1309
- config,
1310
- isSudo: false,
1311
- })
1312
- await validateQueryFieldReadAccess({
1313
- where: args?.where,
1314
- orderBy: args?.orderBy,
1315
- listConfig,
1316
- listName,
1317
- session: context.session,
1318
- context,
1319
- isSudo: false,
1320
- })
1321
-
1322
- // #916 — scope every relation filter nested in `where`
1323
- // (`some`/`every`/`none`/`is`/`isNot`) by the RELATED list's own `query`
1324
- // access, recursing through every hop of a chain — the `where`
1325
- // counterpart to how `include` is already scoped below via
1326
- // `buildAccessScopedInclude`. Runs after the checks above for the same
1327
- // ordering reason: only once the caller is known to have SOME access to
1328
- // THIS list.
1329
- const scopedWhere = args?.where
1330
- ? ((await buildAccessScopedWhere(args.where, listConfig, listName, config, {
1331
- session: context.session,
1332
- context,
1333
- })) as Record<string, unknown>)
1334
- : args?.where
1335
-
1336
- const mergedWhere = mergeFilters(scopedWhere, accessResult)
1337
- if (mergedWhere === null) {
1338
- return []
1339
- }
1340
- where = mergedWhere
1341
- }
1342
-
1343
- const fragment = isFragment(args?.query) ? args.query : null
1344
-
1345
- // Resolve `include`, folding any declared dependencies (`needs`,
1346
- // ADR-0025) in alongside whatever the fragment/caller/sudo/bare path
1347
- // already produces — see `resolveReadInclude`'s doc comment.
1348
- let { include, declaredOnly, selection, toOneAccessFilters, countDenials } =
1349
- await resolveReadInclude(
1350
- args?.include,
1351
- fragment ? fragment._fields : undefined,
1352
- listName,
1353
- listConfig,
1354
- context,
1355
- config,
1356
- )
1357
-
1358
- // Strips virtual keys from `include` before the Prisma call — see the
1359
- // `createFindUnique` comment above for why (#628, ADR-0027).
1360
- include = stripVirtualFieldsFromInclude(include, listConfig.fields, config)
1361
-
1362
- // Access Prisma model dynamically - required because model names are generated at runtime
1363
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1364
- const model = (prisma as any)[getDbKey(listName)]
1365
- const items = await model.findMany({
1366
- where,
1367
- orderBy: args?.orderBy,
1368
- take: args?.take,
1369
- skip: args?.skip,
1370
- include,
1371
- })
1372
-
1373
- // Resolve which of the to-one relations flagged by `toOneAccessFilters`
1374
- // actually survive their related list's `query` access (issue #974) —
1375
- // ONE batched existence check per relation across every row in `items`,
1376
- // before field visibility runs on any of them.
1377
- const toOneVisibility = await resolveToOneAccessVisibility(items, toOneAccessFilters, {
1378
- session: context.session,
1379
- context,
1380
- })
1381
-
1382
- // Pass sudo flag through context to skip field-level access checks
1383
- const filtered = await Promise.all(
1384
- items.map((item: Record<string, unknown>) =>
1385
- filterReadableFields(
1386
- item,
1387
- listConfig.fields,
1388
- {
1389
- session: context.session,
1390
- context: { ...context, _isSudo: context._isSudo },
1391
- },
1392
- config,
1393
- 0,
1394
- listName,
1395
- declaredOnly,
1396
- selection,
1397
- toOneVisibility,
1398
- countDenials,
1399
- ),
1400
- ),
1401
- )
1402
-
1403
- if (fragment) {
1404
- return filtered.map((item: Record<string, unknown>) => pickFields(item, fragment._fields))
1405
- }
1406
-
1407
- return filtered
1408
- }
1409
- }
1410
-
1411
- /**
1412
- * Create findFirst operation with access control.
1413
- *
1414
- * findFirst is sugar over the access-controlled findMany: it runs the exact same
1415
- * query-access checks and access-controlled include building as findMany, then
1416
- * returns the first matching row (or null when nothing matches). This introduces
1417
- * no new access surface — it inherits findMany's silent-failure contract (an
1418
- * access-denied query yields `[]`, which becomes `null` here).
1419
- */
1420
- function createFindFirst(findManyOp: ReturnType<typeof createFindMany>) {
1421
- return async (args?: {
1422
- where?: Record<string, unknown>
1423
- orderBy?: Record<string, 'asc' | 'desc'> | Array<Record<string, 'asc' | 'desc'>>
1424
- skip?: number
1425
- include?: Record<string, unknown>
1426
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1427
- query?: any
1428
- // `select` is not honoured — accepted only so the no-op can be made visible.
1429
- select?: Record<string, unknown>
1430
- }) => {
1431
- const result = await findManyOp({ ...args, take: 1 })
1432
- return result[0] ?? null
1433
- }
1434
- }
1435
-
1436
- function createCreate<TPrisma extends PrismaClientLike>(
1437
- listName: string,
1438
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1439
- listConfig: ListConfig<any>,
1440
- prisma: TPrisma,
1441
- context: AccessContext<TPrisma>,
1442
- config: OpenSaasConfig,
1443
- ) {
1444
- // Thin adapter over the Write Pipeline: pick the create strategy, run the
1445
- // canonical secured write sequence, return its result.
1446
- return async (args: { data: Record<string, unknown> }) => {
1447
- return runWritePipeline({
1448
- listName,
1449
- listConfig,
1450
- prisma,
1451
- context,
1452
- config,
1453
- inputData: args.data,
1454
- strategy: createWriteStrategy(listName, listConfig, context),
1455
- })
1456
- }
1457
- }
1458
-
1459
- // Runs create in a loop (not Prisma's native createMany) so every item still
1460
- // gets its own hooks and access control.
1461
- function createCreateMany<TPrisma extends PrismaClientLike>(
1462
- listName: string,
1463
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1464
- listConfig: ListConfig<any>,
1465
- prisma: TPrisma,
1466
- context: AccessContext<TPrisma>,
1467
- config: OpenSaasConfig,
1468
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1469
- createFn: any,
1470
- ) {
1471
- return async (args: { data: Record<string, unknown>[] }) => {
1472
- const results = []
1473
-
1474
- for (const item of args.data) {
1475
- const result = await createFn({ data: item })
1476
- results.push(result)
1477
- }
1478
-
1479
- return results
1480
- }
1481
- }
1482
-
1483
- function createUpdate<TPrisma extends PrismaClientLike>(
1484
- listName: string,
1485
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1486
- listConfig: ListConfig<any>,
1487
- prisma: TPrisma,
1488
- context: AccessContext<TPrisma>,
1489
- config: OpenSaasConfig,
1490
- ) {
1491
- // Thin adapter over the Write Pipeline: pick the update strategy, run the
1492
- // canonical secured write sequence, return its result.
1493
- return async (args: { where: { id: string }; data: Record<string, unknown> }) => {
1494
- return runWritePipeline({
1495
- listName,
1496
- listConfig,
1497
- prisma,
1498
- context,
1499
- config,
1500
- inputData: args.data,
1501
- strategy: updateWriteStrategy(listConfig, context, args.where),
1502
- })
1503
- }
1504
- }
1505
-
1506
- // Finds matching records, then updates each individually (not Prisma's native
1507
- // updateMany) so every item still gets its own hooks and access control.
1508
- function createUpdateMany<TPrisma extends PrismaClientLike>(
1509
- listName: string,
1510
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1511
- listConfig: ListConfig<any>,
1512
- prisma: TPrisma,
1513
- context: AccessContext<TPrisma>,
1514
- config: OpenSaasConfig,
1515
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1516
- findManyFn: any,
1517
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1518
- updateFn: any,
1519
- ) {
1520
- return async (args: { where?: Record<string, unknown>; data: Record<string, unknown> }) => {
1521
- const items = await findManyFn({ where: args.where })
1522
-
1523
- const results = []
1524
- for (const item of items) {
1525
- const result = await updateFn({ where: { id: item.id }, data: args.data })
1526
- results.push(result)
1527
- }
1528
-
1529
- return results
1530
- }
1531
- }
1532
-
1533
- function createDelete<TPrisma extends PrismaClientLike>(
1534
- listName: string,
1535
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1536
- listConfig: ListConfig<any>,
1537
- prisma: TPrisma,
1538
- context: AccessContext<TPrisma>,
1539
- config: OpenSaasConfig,
1540
- ) {
1541
- // Thin adapter over the Write Pipeline: pick the delete strategy, run the
1542
- // canonical secured write sequence, return its result.
1543
- return async (args: { where: { id: string } }) => {
1544
- return runWritePipeline({
1545
- listName,
1546
- listConfig,
1547
- prisma,
1548
- context,
1549
- config,
1550
- inputData: undefined,
1551
- strategy: deleteWriteStrategy(listName, listConfig, context, args.where),
1552
- })
1553
- }
1554
- }
1555
-
1556
- function createCount<TPrisma extends PrismaClientLike>(
1557
- listName: string,
1558
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1559
- listConfig: ListConfig<any>,
1560
- prisma: TPrisma,
1561
- context: AccessContext<TPrisma>,
1562
- config: OpenSaasConfig,
1563
- ) {
1564
- return async (args?: { where?: Record<string, unknown> }) => {
1565
- // Check query access first (skip if sudo mode) — this MUST run before the
1566
- // #912/#915 where validation below. See the comment there for why.
1567
- let where: Record<string, unknown> | undefined = args?.where
1568
- if (!context._isSudo) {
1569
- const queryAccess = listConfig.access?.operation?.query
1570
- const accessResult = await checkAccess(queryAccess, {
1571
- session: context.session,
1572
- context,
1573
- })
1574
-
1575
- if (accessResult === false) {
1576
- return 0
1577
- }
1578
-
1579
- // #912 — reject a `where` key the list config doesn't declare (e.g. a
1580
- // Prisma-generated back-relation), and #915 — reject one naming a field
1581
- // this session cannot READ. `count` leaks the most cleanly of any read
1582
- // op — a bare count answers a predicate with no rows returned at all —
1583
- // so it gets the same reject, not a lesser one. Both run only now that
1584
- // the caller is known to have SOME access to the list (`accessResult
1585
- // !== false`) — see the identical comment in `createFindMany` for why
1586
- // that ordering matters: running them before the access check would
1587
- // let a fully-denied caller learn a field's name and read-gating
1588
- // status from the thrown error alone. `sudo` bypasses this whole
1589
- // branch, matching the write path.
1590
- validateQueryKeys({
1591
- where: args?.where,
1592
- listConfig,
1593
- listName,
1594
- config,
1595
- isSudo: false,
1596
- })
1597
- await validateQueryFieldReadAccess({
1598
- where: args?.where,
1599
- listConfig,
1600
- listName,
1601
- session: context.session,
1602
- context,
1603
- isSudo: false,
1604
- })
1605
-
1606
- // #916 — scope every relation filter nested in `where` by the RELATED
1607
- // list's own `query` access. See the identical comment in
1608
- // `createFindMany` for why this runs here, in this order.
1609
- const scopedWhere = args?.where
1610
- ? ((await buildAccessScopedWhere(args.where, listConfig, listName, config, {
1611
- session: context.session,
1612
- context,
1613
- })) as Record<string, unknown>)
1614
- : args?.where
1615
-
1616
- const mergedWhere = mergeFilters(scopedWhere, accessResult)
1617
- if (mergedWhere === null) {
1618
- return 0
1619
- }
1620
- where = mergedWhere
1621
- }
1622
-
1623
- // Access Prisma model dynamically - required because model names are generated at runtime
1624
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1625
- const model = (prisma as any)[getDbKey(listName)]
1626
- const count = await model.count({
1627
- where,
1628
- })
1629
-
1630
- return count
1631
- }
1632
- }
1633
-
1634
- function createGet<TPrisma extends PrismaClientLike>(
1635
- listName: string,
1636
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1637
- listConfig: ListConfig<any>,
1638
- prisma: TPrisma,
1639
- context: AccessContext<TPrisma>,
1640
- config: OpenSaasConfig,
1641
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1642
- createFn: any,
1643
- ) {
1644
- return async (args?: {
1645
- include?: Record<string, unknown>
1646
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1647
- query?: any
1648
- // `select` is not honoured — accepted only so the no-op can be made visible.
1649
- select?: Record<string, unknown>
1650
- }) => {
1651
- warnIfSelectIgnored(args, listName, 'get')
1652
-
1653
- // Access Prisma model dynamically - required because model names are generated at runtime
1654
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1655
- const model = (prisma as any)[getDbKey(listName)]
1656
-
1657
- let where: Record<string, unknown> = {}
1658
- if (!context._isSudo) {
1659
- const queryAccess = listConfig.access?.operation?.query
1660
- const accessResult = await checkAccess(queryAccess, {
1661
- session: context.session,
1662
- context,
1663
- })
1664
-
1665
- if (accessResult === false) {
1666
- return null
1667
- }
1668
-
1669
- // A singleton has no per-record `where`, so the access filter (if any) is
1670
- // the whole `where`.
1671
- if (accessResult && typeof accessResult === 'object') {
1672
- where = accessResult
1673
- }
1674
- }
1675
-
1676
- // Access control still runs via filterReadableFields even though a
1677
- // fragment drives `include`; the fragment only narrows which fields come back.
1678
- const fragment = isFragment(args?.query) ? args.query : null
1679
-
1680
- // Resolve `include`, folding any declared dependencies (`needs`,
1681
- // ADR-0025) in alongside whatever the fragment/caller/sudo/bare path
1682
- // already produces — see `resolveReadInclude`'s doc comment.
1683
- let { include, declaredOnly, selection, toOneAccessFilters, countDenials } =
1684
- await resolveReadInclude(
1685
- args?.include,
1686
- fragment ? fragment._fields : undefined,
1687
- listName,
1688
- listConfig,
1689
- context,
1690
- config,
1691
- )
1692
-
1693
- // Virtual fields have no database column and must never reach Prisma (#628).
1694
- include = stripVirtualFieldsFromInclude(include, listConfig.fields, config)
1695
-
1696
- const item = await model.findFirst({
1697
- where,
1698
- include,
1699
- })
1700
-
1701
- if (item) {
1702
- // Resolve which of the to-one relations flagged by `toOneAccessFilters`
1703
- // actually survive their related list's `query` access (issue #974).
1704
- const toOneVisibility = await resolveToOneAccessVisibility([item], toOneAccessFilters, {
1705
- session: context.session,
1706
- context,
1707
- })
1708
-
1709
- const filtered = await filterReadableFields(
1710
- item,
1711
- listConfig.fields,
1712
- {
1713
- session: context.session,
1714
- context: { ...context, _isSudo: context._isSudo },
1715
- },
1716
- config,
1717
- 0,
1718
- listName,
1719
- declaredOnly,
1720
- selection,
1721
- toOneVisibility,
1722
- countDenials,
1723
- )
1724
- if (fragment) {
1725
- return pickFields(filtered, fragment._fields)
1726
- }
1727
- return filtered
1728
- }
1729
-
1730
- if (shouldAutoCreate(listConfig)) {
1731
- const defaultData = getDefaultData(listConfig)
1732
- return await createFn({ data: defaultData })
1733
- }
1734
-
1735
- return null
1736
- }
1737
- }