@opensaas/stack-core 0.42.3 → 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 +2745 -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 -15
  204. package/dist/index.d.ts.map +1 -1
  205. package/dist/index.js +105 -44
  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 -47
  464. package/dist/context/nested-operations.d.ts.map +0 -1
  465. package/dist/context/nested-operations.js +0 -731
  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 -1325
  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 -184
  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 -3141
  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 -231
  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,1901 +0,0 @@
1
- import { z } from 'zod'
2
- import type {
3
- TextField,
4
- IntegerField,
5
- DecimalField,
6
- BigIntField,
7
- CheckboxField,
8
- TimestampField,
9
- CalendarDayField,
10
- PasswordField,
11
- SelectField,
12
- RelationshipField,
13
- JsonField,
14
- VirtualField,
15
- OpenSaasConfig,
16
- FieldConfig,
17
- PrismaRelationResult,
18
- } from '../config/types.js'
19
- import { hashPassword, isHashedPassword, HashedPassword } from '../utils/password.js'
20
- import { formatPrismaDefault } from './format-prisma-default.js'
21
- import { getLabelFieldName } from '../config/label.js'
22
- import type { FilterOperator, FilterSpec } from '../filter/types.js'
23
- import { RELATIONSHIP_COUNT_FILTER_KEY } from '../filter/types.js'
24
-
25
- /** Operators shared by numeric/date fields' `getFilterSpec`. */
26
- const COMPARISON_OPERATORS: FilterOperator[] = ['eq', 'gt', 'gte', 'lt', 'lte']
27
-
28
- function prismaComparisonKey(operator: FilterOperator): string {
29
- return operator === 'eq' ? 'equals' : operator
30
- }
31
-
32
- // Field-config types live here, alongside the builders that produce them.
33
- // (The umbrella `FieldConfig` and authoring `BaseFieldConfig` stay on the root
34
- // and `/extend` entry points respectively.)
35
- export type {
36
- TextField,
37
- IntegerField,
38
- DecimalField,
39
- BigIntField,
40
- CheckboxField,
41
- TimestampField,
42
- CalendarDayField,
43
- PasswordField,
44
- SelectField,
45
- SelectOption,
46
- SelectOptionVariant,
47
- RelationshipField,
48
- JsonField,
49
- VirtualField,
50
- PrismaRelationResult,
51
- MultiColumnPrismaResult,
52
- } from '../config/types.js'
53
-
54
- function formatFieldName(fieldName: string): string {
55
- return fieldName
56
- .replace(/([A-Z])/g, ' $1')
57
- .replace(/^./, (str) => str.toUpperCase())
58
- .trim()
59
- }
60
-
61
- /**
62
- * Text field
63
- */
64
- export function text<
65
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
66
- >(options?: Omit<TextField<TTypeInfo>, 'type'>): TextField<TTypeInfo> {
67
- return {
68
- type: 'text',
69
- ...options,
70
- getZodSchema: (fieldName: string, operation: 'create' | 'update') => {
71
- const validation = options?.validation
72
- const isRequired = validation?.isRequired
73
- const length = validation?.length
74
- const minLength = length?.min && length.min > 0 ? length.min : 1
75
-
76
- const baseSchema = z.string({
77
- message: `${formatFieldName(fieldName)} must be text`,
78
- })
79
-
80
- const withMin =
81
- isRequired || length?.min !== undefined
82
- ? baseSchema.min(minLength, {
83
- message:
84
- minLength > 1
85
- ? `${formatFieldName(fieldName)} must be at least ${minLength} characters`
86
- : `${formatFieldName(fieldName)} is required`,
87
- })
88
- : baseSchema
89
-
90
- const withMax =
91
- length?.max !== undefined
92
- ? withMin.max(length.max, {
93
- message: `${formatFieldName(fieldName)} must be at most ${length.max} characters`,
94
- })
95
- : withMin
96
-
97
- if (isRequired && operation === 'update') {
98
- return withMax.optional()
99
- }
100
-
101
- return !isRequired ? withMax.optional().nullable() : withMax
102
- },
103
- getPrismaType: (
104
- _fieldName: string,
105
- _provider?: string,
106
- _listName?: string,
107
- keystoneCompat?: boolean,
108
- ) => {
109
- const validation = options?.validation
110
- const db = options?.db
111
- const isRequired = validation?.isRequired
112
- const isNullable = db?.isNullable ?? !isRequired
113
- let modifiers = ''
114
-
115
- if (isNullable) {
116
- modifiers += '?'
117
- }
118
-
119
- if (db?.nativeType) {
120
- modifiers += ` @db.${db.nativeType}`
121
- }
122
-
123
- // Default value. An explicit `defaultValue` always wins. When none is set
124
- // and Keystone-compat mode is on, a non-null text column gets Keystone's
125
- // implicit empty-string default. Both go through formatPrismaDefault, so
126
- // the empty-string literal (`""`) is produced the same way as any other
127
- // text default. Independent of the nullable `?` modifier above — the
128
- // default never overwrites nullability.
129
- const defaultSource =
130
- options?.defaultValue !== undefined
131
- ? options.defaultValue
132
- : keystoneCompat && !isNullable
133
- ? ''
134
- : undefined
135
- const defaultLiteral = formatPrismaDefault(defaultSource, 'text')
136
- if (defaultLiteral !== undefined) {
137
- modifiers += ` @default(${defaultLiteral})`
138
- }
139
-
140
- // Unique modifier. A non-unique index has no field-level form in Prisma,
141
- // so it is requested out-of-line via `index` below and emitted by the
142
- // generator as `@@index([...])` on the model.
143
- if (options?.isIndexed === 'unique') {
144
- modifiers += ' @unique'
145
- }
146
-
147
- if (db?.map) {
148
- modifiers += ` @map("${db.map}")`
149
- }
150
-
151
- return {
152
- type: 'String',
153
- modifiers: modifiers.trimStart() || undefined,
154
- index: options?.isIndexed === true ? true : undefined,
155
- }
156
- },
157
- getTypeScriptType: () => {
158
- const validation = options?.validation
159
- const isRequired = validation?.isRequired
160
-
161
- return {
162
- type: 'string',
163
- optional: !isRequired,
164
- }
165
- },
166
- getFilterSpec: (fieldName: string): FilterSpec => ({
167
- operators: ['eq'],
168
- freeText: true,
169
- toCondition: (operator, value) =>
170
- operator === 'eq' ? { [fieldName]: { contains: value } } : null,
171
- suggestions: { valueSource: { kind: 'none' } },
172
- }),
173
- }
174
- }
175
-
176
- /**
177
- * Integer field
178
- */
179
- export function integer<
180
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
181
- >(options?: Omit<IntegerField<TTypeInfo>, 'type'>): IntegerField<TTypeInfo> {
182
- return {
183
- type: 'integer',
184
- ...options,
185
- getZodSchema: (fieldName: string, operation: 'create' | 'update') => {
186
- const baseSchema = z.number({
187
- message: `${formatFieldName(fieldName)} must be a number`,
188
- })
189
-
190
- const withMin =
191
- options?.validation?.min !== undefined
192
- ? baseSchema.min(options.validation.min, {
193
- message: `${formatFieldName(fieldName)} must be at least ${options.validation.min}`,
194
- })
195
- : baseSchema
196
-
197
- const withMax =
198
- options?.validation?.max !== undefined
199
- ? withMin.max(options.validation.max, {
200
- message: `${formatFieldName(fieldName)} must be at most ${options.validation.max}`,
201
- })
202
- : withMin
203
-
204
- return !options?.validation?.isRequired || operation === 'update'
205
- ? withMax.optional().nullable()
206
- : withMax
207
- },
208
- getPrismaType: (_fieldName: string) => {
209
- const validation = options?.validation
210
- const db = options?.db
211
- const isRequired = validation?.isRequired
212
- const isNullable = db?.isNullable ?? !isRequired
213
- let modifiers = ''
214
-
215
- if (isNullable) {
216
- modifiers += '?'
217
- }
218
-
219
- if (db?.nativeType) {
220
- modifiers += ` @db.${db.nativeType}`
221
- }
222
-
223
- const defaultLiteral = formatPrismaDefault(options?.defaultValue, 'integer')
224
- if (defaultLiteral !== undefined) {
225
- modifiers += ` @default(${defaultLiteral})`
226
- }
227
-
228
- if (db?.map) {
229
- modifiers += ` @map("${db.map}")`
230
- }
231
-
232
- // Unique modifier — non-unique index routes through `index` below,
233
- // same as `text()`'s getPrismaType.
234
- if (options?.isIndexed === 'unique') {
235
- modifiers += ' @unique'
236
- }
237
-
238
- return {
239
- type: 'Int',
240
- modifiers: modifiers.trimStart() || undefined,
241
- index: options?.isIndexed === true ? true : undefined,
242
- }
243
- },
244
- getTypeScriptType: () => {
245
- const isRequired = options?.validation?.isRequired
246
-
247
- return {
248
- type: 'number',
249
- optional: !isRequired,
250
- }
251
- },
252
- // A non-integer token can't be interpreted, so it degrades to free text.
253
- getFilterSpec: (fieldName: string): FilterSpec => ({
254
- operators: COMPARISON_OPERATORS,
255
- toCondition: (operator, value) => {
256
- const trimmed = value.trim()
257
- if (!/^-?\d+$/.test(trimmed)) return null
258
- return { [fieldName]: { [prismaComparisonKey(operator)]: Number(trimmed) } }
259
- },
260
- suggestions: { valueSource: { kind: 'none' } },
261
- }),
262
- }
263
- }
264
-
265
- /**
266
- * Decimal field for precise numeric values (e.g., currency, measurements)
267
- *
268
- * **Features:**
269
- * - Stores decimal numbers with configurable precision and scale
270
- * - Uses Prisma's Decimal type (backed by decimal.js for precision)
271
- * - Default precision: 18 digits, scale: 4 decimal places
272
- * - Validation for min/max values
273
- * - Optional database column mapping and nullability control
274
- * - Index support (boolean or 'unique')
275
- *
276
- * **Usage Example:**
277
- * ```typescript
278
- * // In opensaas.config.ts
279
- * fields: {
280
- * price: decimal({
281
- * precision: 10,
282
- * scale: 2,
283
- * validation: {
284
- * isRequired: true,
285
- * min: '0',
286
- * max: '999999.99'
287
- * }
288
- * }),
289
- * coordinates: decimal({
290
- * precision: 18,
291
- * scale: 8,
292
- * db: { map: 'coord_value' }
293
- * })
294
- * }
295
- *
296
- * // Creating with decimal values
297
- * const product = await context.db.product.create({
298
- * data: {
299
- * price: '19.99', // Can use string
300
- * // price: 19.99, // or number (converted to Decimal)
301
- * }
302
- * })
303
- * ```
304
- *
305
- * @param options - Field configuration options
306
- * @returns Decimal field configuration
307
- */
308
- export function decimal<
309
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
310
- >(options?: Omit<DecimalField<TTypeInfo>, 'type'>): DecimalField<TTypeInfo> {
311
- const precision = options?.precision ?? 18
312
- const scale = options?.scale ?? 4
313
-
314
- return {
315
- type: 'decimal',
316
- precision,
317
- scale,
318
- ...options,
319
- getZodSchema: (fieldName: string, operation: 'create' | 'update') => {
320
- const baseSchema = z.union(
321
- [
322
- z.string({
323
- message: `${formatFieldName(fieldName)} must be a decimal value (string or number)`,
324
- }),
325
- z.number({
326
- message: `${formatFieldName(fieldName)} must be a decimal value (string or number)`,
327
- }),
328
- ],
329
- {
330
- message: `${formatFieldName(fieldName)} must be a decimal value`,
331
- },
332
- )
333
-
334
- let schema = baseSchema
335
-
336
- if (options?.validation?.min !== undefined) {
337
- const minValue = parseFloat(options.validation.min)
338
- schema = schema.refine(
339
- (val) => {
340
- const numVal = typeof val === 'string' ? parseFloat(val) : val
341
- return !isNaN(numVal) && numVal >= minValue
342
- },
343
- {
344
- message: `${formatFieldName(fieldName)} must be at least ${options.validation.min}`,
345
- },
346
- )
347
- }
348
-
349
- if (options?.validation?.max !== undefined) {
350
- const maxValue = parseFloat(options.validation.max)
351
- schema = schema.refine(
352
- (val) => {
353
- const numVal = typeof val === 'string' ? parseFloat(val) : val
354
- return !isNaN(numVal) && numVal <= maxValue
355
- },
356
- {
357
- message: `${formatFieldName(fieldName)} must be at most ${options.validation.max}`,
358
- },
359
- )
360
- }
361
-
362
- return !options?.validation?.isRequired || operation === 'update'
363
- ? schema.optional().nullable()
364
- : schema
365
- },
366
- getPrismaType: (_fieldName: string) => {
367
- const validation = options?.validation
368
- const db = options?.db
369
- const isRequired = validation?.isRequired
370
- const isNullable = db?.isNullable ?? !isRequired
371
-
372
- let modifiers = ''
373
-
374
- if (isNullable) {
375
- modifiers += '?'
376
- }
377
-
378
- modifiers += ` @db.Decimal(${precision}, ${scale})`
379
-
380
- if (options?.defaultValue !== undefined) {
381
- modifiers += ` @default(${options.defaultValue})`
382
- }
383
-
384
- if (db?.map) {
385
- modifiers += ` @map("${db.map}")`
386
- }
387
-
388
- // Unique modifier — non-unique index routes through `index` below,
389
- // same as `text()`'s getPrismaType.
390
- if (options?.isIndexed === 'unique') {
391
- modifiers += ' @unique'
392
- }
393
-
394
- return {
395
- type: 'Decimal',
396
- modifiers: modifiers.trimStart() || undefined,
397
- index: options?.isIndexed === true ? true : undefined,
398
- }
399
- },
400
- getTypeScriptType: () => {
401
- const validation = options?.validation
402
- const db = options?.db
403
- const isRequired = validation?.isRequired
404
- const isNullable = db?.isNullable ?? !isRequired
405
-
406
- return {
407
- type: "import('decimal.js').Decimal",
408
- optional: isNullable,
409
- }
410
- },
411
- getTypeScriptImports: () => {
412
- return [
413
- {
414
- names: ['Decimal'],
415
- from: 'decimal.js',
416
- typeOnly: true,
417
- },
418
- ]
419
- },
420
- // Decimals compare like integers, but the value stays a string so Prisma's
421
- // Decimal keeps full precision. A non-numeric value degrades to free text.
422
- getFilterSpec: (fieldName: string): FilterSpec => ({
423
- operators: COMPARISON_OPERATORS,
424
- toCondition: (operator, value) => {
425
- const trimmed = value.trim()
426
- if (!/^-?\d+(\.\d+)?$/.test(trimmed)) return null
427
- return { [fieldName]: { [prismaComparisonKey(operator)]: trimmed } }
428
- },
429
- suggestions: { valueSource: { kind: 'none' } },
430
- }),
431
- }
432
- }
433
-
434
- /**
435
- * 64-bit integer field for values that overflow `integer()`'s 32-bit `Int`
436
- * (e.g. a millisecond epoch). Prisma `BigInt`, TypeScript `bigint`.
437
- *
438
- * Accepts `bigint`, an integer `number`, or a numeric `string` on write and
439
- * always coerces to `bigint`. A `number` above `Number.MAX_SAFE_INTEGER` is
440
- * rejected rather than coerced — it has already lost precision before this
441
- * field sees it, so accepting it would reintroduce the exact defect this
442
- * field exists to prevent. Pass a `bigint` or a string for values beyond that
443
- * range.
444
- *
445
- * Wire representation (ADR-0029): `bigint` in application code, a decimal
446
- * string over MCP.
447
- */
448
- export function bigInt<
449
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
450
- >(options?: Omit<BigIntField<TTypeInfo>, 'type'>): BigIntField<TTypeInfo> {
451
- return {
452
- type: 'bigInt',
453
- ...options,
454
- getZodSchema: (fieldName: string, operation: 'create' | 'update') => {
455
- const validation = options?.validation
456
- const isRequired = validation?.isRequired
457
-
458
- const coerced = z
459
- .union([z.bigint(), z.number(), z.string()], {
460
- message: `${formatFieldName(fieldName)} must be a bigint, an integer number, or a numeric string`,
461
- })
462
- .transform((val, ctx) => {
463
- if (typeof val === 'bigint') return val
464
-
465
- if (typeof val === 'number') {
466
- if (!Number.isInteger(val)) {
467
- ctx.addIssue(`${formatFieldName(fieldName)} must be an integer`)
468
- return z.NEVER
469
- }
470
- if (!Number.isSafeInteger(val)) {
471
- ctx.addIssue(
472
- `${formatFieldName(fieldName)} exceeds Number.MAX_SAFE_INTEGER — pass a bigint or a numeric string instead`,
473
- )
474
- return z.NEVER
475
- }
476
- return BigInt(val)
477
- }
478
-
479
- const trimmed = val.trim()
480
- if (!/^-?\d+$/.test(trimmed)) {
481
- ctx.addIssue(`${formatFieldName(fieldName)} must be an integer`)
482
- return z.NEVER
483
- }
484
- return BigInt(trimmed)
485
- })
486
-
487
- let schema = coerced
488
-
489
- if (validation?.min !== undefined) {
490
- const min = validation.min
491
- schema = schema.refine((val) => val >= min, {
492
- message: `${formatFieldName(fieldName)} must be at least ${min}`,
493
- })
494
- }
495
-
496
- if (validation?.max !== undefined) {
497
- const max = validation.max
498
- schema = schema.refine((val) => val <= max, {
499
- message: `${formatFieldName(fieldName)} must be at most ${max}`,
500
- })
501
- }
502
-
503
- return !isRequired || operation === 'update' ? schema.optional().nullable() : schema
504
- },
505
- getPrismaType: (_fieldName: string) => {
506
- const validation = options?.validation
507
- const db = options?.db
508
- const isRequired = validation?.isRequired
509
- const isNullable = db?.isNullable ?? !isRequired
510
- let modifiers = ''
511
-
512
- if (isNullable) {
513
- modifiers += '?'
514
- }
515
-
516
- if (db?.nativeType) {
517
- modifiers += ` @db.${db.nativeType}`
518
- }
519
-
520
- if (options?.defaultValue !== undefined) {
521
- modifiers += ` @default(${options.defaultValue})`
522
- }
523
-
524
- if (db?.map) {
525
- modifiers += ` @map("${db.map}")`
526
- }
527
-
528
- // Unique modifier — non-unique index routes through `index` below,
529
- // same as `text()`'s getPrismaType.
530
- if (options?.isIndexed === 'unique') {
531
- modifiers += ' @unique'
532
- }
533
-
534
- return {
535
- type: 'BigInt',
536
- modifiers: modifiers.trimStart() || undefined,
537
- index: options?.isIndexed === true ? true : undefined,
538
- }
539
- },
540
- getTypeScriptType: () => {
541
- const isRequired = options?.validation?.isRequired
542
-
543
- return {
544
- type: 'bigint',
545
- optional: !isRequired,
546
- }
547
- },
548
- // A non-integer token degrades to free text.
549
- getFilterSpec: (fieldName: string): FilterSpec => ({
550
- operators: COMPARISON_OPERATORS,
551
- toCondition: (operator, value) => {
552
- const trimmed = value.trim()
553
- if (!/^-?\d+$/.test(trimmed)) return null
554
- return { [fieldName]: { [prismaComparisonKey(operator)]: BigInt(trimmed) } }
555
- },
556
- suggestions: { valueSource: { kind: 'none' } },
557
- }),
558
- }
559
- }
560
-
561
- /**
562
- * Checkbox (boolean) field
563
- */
564
- export function checkbox<
565
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
566
- >(options?: Omit<CheckboxField<TTypeInfo>, 'type'>): CheckboxField<TTypeInfo> {
567
- return {
568
- type: 'checkbox',
569
- ...options,
570
- getZodSchema: () => {
571
- return z.boolean().optional().nullable()
572
- },
573
- getPrismaType: (_fieldName: string) => {
574
- const db = options?.db
575
- const hasDefault = options?.defaultValue !== undefined
576
- let modifiers = ''
577
-
578
- // Checkboxes are non-nullable by default (must be true or false), unlike
579
- // the other scalar fields' nullable-unless-required default — set
580
- // db.isNullable: true to allow NULL.
581
- if (db?.isNullable === true) {
582
- modifiers += '?'
583
- }
584
-
585
- if (hasDefault) {
586
- modifiers += ` @default(${options.defaultValue})`
587
- }
588
-
589
- if (db?.map) {
590
- modifiers += ` @map("${db.map}")`
591
- }
592
-
593
- return {
594
- type: 'Boolean',
595
- modifiers: modifiers.trimStart() || undefined,
596
- }
597
- },
598
- getTypeScriptType: () => {
599
- return {
600
- type: 'boolean',
601
- optional: options?.defaultValue === undefined,
602
- }
603
- },
604
- // Anything other than true/false degrades to free text.
605
- getFilterSpec: (fieldName: string): FilterSpec => ({
606
- operators: ['eq'],
607
- toCondition: (operator, value) => {
608
- if (operator !== 'eq') return null
609
- const normalized = value.trim().toLowerCase()
610
- if (normalized === 'true') return { [fieldName]: { equals: true } }
611
- if (normalized === 'false') return { [fieldName]: { equals: false } }
612
- return null
613
- },
614
- suggestions: {
615
- valueSource: {
616
- kind: 'enum',
617
- options: [
618
- { value: 'true', label: 'True' },
619
- { value: 'false', label: 'False' },
620
- ],
621
- },
622
- },
623
- }),
624
- }
625
- }
626
-
627
- /**
628
- * Timestamp (DateTime) field
629
- */
630
- export function timestamp<
631
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
632
- >(options?: Omit<TimestampField<TTypeInfo>, 'type'>): TimestampField<TTypeInfo> {
633
- return {
634
- type: 'timestamp',
635
- ...options,
636
- getZodSchema: () => {
637
- return z.union([z.date(), z.iso.datetime()]).optional().nullable()
638
- },
639
- getPrismaType: (_fieldName: string) => {
640
- const db = options?.db
641
- const hasDefaultNow =
642
- options?.defaultValue &&
643
- typeof options.defaultValue === 'object' &&
644
- 'kind' in options.defaultValue &&
645
- options.defaultValue.kind === 'now'
646
-
647
- const isNullable = db?.isNullable ?? !hasDefaultNow
648
-
649
- let modifiers = ''
650
-
651
- if (isNullable) {
652
- modifiers += '?'
653
- }
654
-
655
- if (hasDefaultNow) {
656
- modifiers += ' @default(now())'
657
- }
658
-
659
- if (db?.nativeType) {
660
- modifiers += ` @db.${db.nativeType}`
661
- }
662
-
663
- if (db?.map) {
664
- modifiers += ` @map("${db.map}")`
665
- }
666
-
667
- // Unique modifier — non-unique index routes through `index` below,
668
- // same as `text()`'s getPrismaType.
669
- if (options?.isIndexed === 'unique') {
670
- modifiers += ' @unique'
671
- }
672
-
673
- return {
674
- type: 'DateTime',
675
- modifiers: modifiers.trimStart() || undefined,
676
- index: options?.isIndexed === true ? true : undefined,
677
- }
678
- },
679
- getTypeScriptType: () => {
680
- const hasDefault =
681
- options?.defaultValue &&
682
- typeof options.defaultValue === 'object' &&
683
- 'kind' in options.defaultValue &&
684
- options.defaultValue.kind === 'now'
685
-
686
- return {
687
- type: 'Date',
688
- optional: !hasDefault,
689
- }
690
- },
691
- // An unparseable date degrades to free text.
692
- getFilterSpec: (fieldName: string): FilterSpec => ({
693
- operators: COMPARISON_OPERATORS,
694
- toCondition: (operator, value) => {
695
- const date = new Date(value.trim())
696
- if (Number.isNaN(date.getTime())) return null
697
- return { [fieldName]: { [prismaComparisonKey(operator)]: date } }
698
- },
699
- suggestions: { valueSource: { kind: 'none' } },
700
- }),
701
- }
702
- }
703
-
704
- /**
705
- * Calendar Day field - date only (no time) in ISO8601 format
706
- *
707
- * Mirrors Keystone's `CalendarDay` scalar: the wire format through
708
- * `context.db.*` is a `YYYY-MM-DD` **string** in both directions (read and
709
- * write). The field's TypeScript type — entity, `CreateInput`, and
710
- * `UpdateInput` — is `string`, so passing a `Date` is a compile-time error.
711
- *
712
- * **Features:**
713
- * - Stores date values only (no time component)
714
- * - PostgreSQL/MySQL: Uses native DATE type via @db.Date
715
- * - SQLite: Uses String representation
716
- * - **Writes:** pass a `YYYY-MM-DD` string (the declared type). A
717
- * `resolveInput` hook converts a valid string to a UTC-midnight `Date`
718
- * before validation, since Prisma 7's client validator rejects a bare date
719
- * string for a `@db.Date` column (#621); a `Date` is also accepted
720
- * directly. A malformed string is rejected at runtime by validation (a
721
- * `ValidationError`). Genuine compile-time rejection of a `Date` at the
722
- * `context.db` call site is tracked in #599.
723
- * - **Reads:** always return a `YYYY-MM-DD` string. Even though the underlying
724
- * `@db.Date` column hands Prisma a `Date`, a `resolveOutput` transform
725
- * normalises it back to a `YYYY-MM-DD` string so the runtime value matches
726
- * the declared `string` type. UTC components are used to avoid timezone
727
- * off-by-one errors.
728
- * - Optional validation for required fields
729
- * - Database column mapping and nullability control
730
- * - Index support (boolean or 'unique')
731
- *
732
- * **Usage Example:**
733
- * ```typescript
734
- * // In opensaas.config.ts
735
- * fields: {
736
- * birthDate: calendarDay({
737
- * validation: { isRequired: true }
738
- * }),
739
- * startDate: calendarDay({
740
- * defaultValue: '2025-01-01',
741
- * db: { map: 'start_date' }
742
- * }),
743
- * endDate: calendarDay({
744
- * isIndexed: true
745
- * })
746
- * }
747
- *
748
- * // Creating with date values — pass YYYY-MM-DD strings (NOT Date objects)
749
- * const event = await context.db.event.create({
750
- * data: {
751
- * startDate: '2025-01-15',
752
- * endDate: '2025-01-20'
753
- * }
754
- * })
755
- *
756
- * // Reading — values come back as YYYY-MM-DD strings
757
- * const e = await context.db.event.findUnique({ where: { id } })
758
- * e?.startDate // => '2025-01-15' (a string, not a Date)
759
- * ```
760
- *
761
- * @param options - Field configuration options
762
- * @returns Calendar Day field configuration
763
- */
764
- export function calendarDay<
765
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
766
- >(options?: Omit<CalendarDayField<TTypeInfo>, 'type'>): CalendarDayField<TTypeInfo> {
767
- return {
768
- type: 'calendarDay',
769
- ...options,
770
- // Hook Pipeline runs field resolveInput before zod validation — the only
771
- // point a YYYY-MM-DD string can be turned into what Prisma's `@db.Date`
772
- // write validator accepts (#621). Reads resolvedData[fieldKey], not raw
773
- // inputData, so a list-level resolveInput's injected default for an
774
- // omitted key is still coerced rather than overwritten.
775
- hooks: {
776
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks must be generic
777
- resolveInput: ({ resolvedData, fieldKey }: { resolvedData: any; fieldKey: string }) => {
778
- const value = resolvedData?.[fieldKey]
779
- if (value == null || value instanceof Date) return value
780
- if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
781
- return new Date(`${value}T00:00:00.000Z`)
782
- }
783
- return value
784
- },
785
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks must be generic
786
- resolveOutput: ({ value }: { value: any }) => formatCalendarDay(value),
787
- ...options?.hooks,
788
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Hook object needs type assertion for field builder
789
- } as any,
790
- getZodSchema: (fieldName: string, operation: 'create' | 'update') => {
791
- const validation = options?.validation
792
- const isRequired = validation?.isRequired
793
-
794
- // Accepts a `Date` because resolveInput above already converted a valid
795
- // string to one before this schema runs; a malformed string falls
796
- // through resolveInput untouched and fails the regex here instead.
797
- const stringSchema = z
798
- .string({
799
- message: `${formatFieldName(fieldName)} must be a valid date in ISO8601 format (YYYY-MM-DD)`,
800
- })
801
- .regex(/^\d{4}-\d{2}-\d{2}$/, {
802
- message: `${formatFieldName(fieldName)} must be in YYYY-MM-DD format`,
803
- })
804
-
805
- const dateSchema = z.union([stringSchema, z.date()])
806
-
807
- if (isRequired && operation === 'create') {
808
- return dateSchema
809
- } else if (isRequired && operation === 'update') {
810
- return dateSchema.optional()
811
- } else {
812
- return dateSchema.optional().nullable()
813
- }
814
- },
815
- getPrismaType: (_fieldName: string, provider?: string) => {
816
- const validation = options?.validation
817
- const db = options?.db
818
- const isRequired = validation?.isRequired
819
- const isNullable = db?.isNullable ?? !isRequired
820
-
821
- let modifiers = ''
822
-
823
- if (isNullable) {
824
- modifiers += '?'
825
- }
826
-
827
- // SQLite has no native DATE type and falls back to TEXT for DateTime
828
- // columns, so @db.Date only applies on PostgreSQL/MySQL.
829
- if (provider && provider.toLowerCase() !== 'sqlite') {
830
- modifiers += ' @db.Date'
831
- }
832
-
833
- if (options?.defaultValue !== undefined) {
834
- modifiers += ` @default("${options.defaultValue}")`
835
- }
836
-
837
- if (db?.map) {
838
- modifiers += ` @map("${db.map}")`
839
- }
840
-
841
- // Unique modifier — non-unique index routes through `index` below,
842
- // same as `text()`'s getPrismaType.
843
- if (options?.isIndexed === 'unique') {
844
- modifiers += ' @unique'
845
- }
846
-
847
- return {
848
- type: 'DateTime',
849
- modifiers: modifiers.trimStart() || undefined,
850
- index: options?.isIndexed === true ? true : undefined,
851
- }
852
- },
853
- getTypeScriptType: () => {
854
- const validation = options?.validation
855
- const db = options?.db
856
- const isRequired = validation?.isRequired
857
- const isNullable = db?.isNullable ?? !isRequired
858
-
859
- return {
860
- type: 'string',
861
- optional: isNullable,
862
- }
863
- },
864
- // Calendar days compare on the `YYYY-MM-DD` value (coerced to a UTC-midnight
865
- // Date so it matches the `@db.Date` column). A malformed value degrades to
866
- // free text.
867
- getFilterSpec: (fieldName: string): FilterSpec => ({
868
- operators: COMPARISON_OPERATORS,
869
- toCondition: (operator, value) => {
870
- const trimmed = value.trim()
871
- if (!/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return null
872
- const date = new Date(`${trimmed}T00:00:00.000Z`)
873
- if (Number.isNaN(date.getTime())) return null
874
- return { [fieldName]: { [prismaComparisonKey(operator)]: date } }
875
- },
876
- suggestions: { valueSource: { kind: 'none' } },
877
- }),
878
- }
879
- }
880
-
881
- /**
882
- * Format a stored calendar-day value to a `YYYY-MM-DD` string.
883
- *
884
- * Handles the value being a `Date` (Postgres/MySQL `@db.Date`), an already
885
- * formatted string (SQLite TEXT fallback), or null/undefined. Dates are
886
- * formatted from their UTC components so the result never drifts a day in
887
- * non-UTC timezones.
888
- */
889
- function formatCalendarDay(value: unknown): string | null | undefined {
890
- if (value === null || value === undefined) {
891
- return value as null | undefined
892
- }
893
-
894
- if (value instanceof Date) {
895
- // toISOString() is UTC; the YYYY-MM-DD prefix is timezone-safe.
896
- return value.toISOString().slice(0, 10)
897
- }
898
-
899
- if (typeof value === 'string') {
900
- // SQLite stores DateTime as TEXT. The value may already be YYYY-MM-DD or a
901
- // full ISO timestamp — take the date-only prefix either way.
902
- return value.slice(0, 10)
903
- }
904
-
905
- // Any other shape is unexpected for a @db.Date column; surface it untouched
906
- // by returning undefined so callers see the field as absent rather than wrong.
907
- return undefined
908
- }
909
-
910
- /**
911
- * Password field (automatically hashed using bcrypt)
912
- *
913
- * **Security Features:**
914
- * - Passwords are automatically hashed during create/update operations
915
- * - Uses bcrypt with cost factor 10 (good balance of security and performance)
916
- * - Already-hashed passwords are not re-hashed (idempotent)
917
- * - Password values in query results include a `compare()` method for authentication
918
- *
919
- * **Usage Example:**
920
- * ```typescript
921
- * // In opensaas.config.ts
922
- * fields: {
923
- * password: password({
924
- * validation: { isRequired: true }
925
- * })
926
- * }
927
- *
928
- * // Creating a user - password is automatically hashed
929
- * const user = await context.db.user.create({
930
- * data: {
931
- * email: 'user@example.com',
932
- * password: 'plaintextPassword' // Automatically hashed before storage
933
- * }
934
- * })
935
- *
936
- * // Authenticating - use the compare() method
937
- * const user = await context.db.user.findUnique({
938
- * where: { email: 'user@example.com' }
939
- * })
940
- *
941
- * if (user && await user.password.compare('plaintextPassword')) {
942
- * // Password is correct - login successful
943
- * }
944
- * ```
945
- *
946
- * **Important Notes:**
947
- * - Password field values are redacted to `{ isSet: boolean }` on serialization
948
- * (`JSON.stringify`, the admin UI). Field-level `read` access is not denied by
949
- * default — configure `access.field.read` if the raw value should never reach
950
- * `context.db` callers at all.
951
- * - Always use the `compare()` method to verify passwords - never compare strings directly
952
- * - The password field value has type `HashedPassword` which extends string with compare()
953
- * - Empty strings and undefined values are skipped (not hashed) to allow partial updates
954
- *
955
- * **Implementation Details:**
956
- * - Uses field-level hooks (`resolveInput` and `resolveOutput`) for automatic transformations
957
- * - The hashing happens via `hooks.resolveInput` during create/update operations
958
- * - The wrapping happens via `hooks.resolveOutput` during read operations
959
- * - This pattern allows third-party field types to define their own transformations
960
- *
961
- * @param options - Field configuration options
962
- * @returns Password field configuration
963
- */
964
- export function password<TTypeInfo extends import('../config/types.js').TypeInfo>(
965
- options?: Omit<PasswordField<TTypeInfo>, 'type'>,
966
- ): PasswordField<TTypeInfo> {
967
- return {
968
- type: 'password',
969
- ...options,
970
- resultExtension: {
971
- outputType: "import('@opensaas/stack-core/internal').HashedPassword",
972
- },
973
- ui: {
974
- ...options?.ui,
975
- // Excluded from default admin table columns (issue #1018) — declared
976
- // via the flag rather than matched by field type/name, so an app can
977
- // still opt a real password field back in with `ui.listView.defaultColumn: true`.
978
- listView: {
979
- defaultColumn: false,
980
- ...options?.ui?.listView,
981
- },
982
- valueForClientSerialization: ({ value }) => ({ isSet: !!value }),
983
- },
984
- hooks: {
985
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks must be generic
986
- resolveInput: async ({ inputData, fieldKey }: { inputData: any; fieldKey: string }) => {
987
- const inputValue = inputData[fieldKey]
988
- if (inputValue === undefined || inputValue === null) {
989
- return inputValue
990
- }
991
-
992
- if (typeof inputValue !== 'string' || inputValue.length === 0) {
993
- return inputValue
994
- }
995
-
996
- // Idempotent: skip re-hashing a value that's already a hash.
997
- if (isHashedPassword(inputValue)) {
998
- return inputValue
999
- }
1000
-
1001
- return (await hashPassword(inputValue)).toString()
1002
- },
1003
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks must be generic
1004
- resolveOutput: ({ value }: { value: any }) => {
1005
- if (typeof value === 'string' && value.length > 0) {
1006
- return new HashedPassword(value)
1007
- }
1008
- return undefined
1009
- },
1010
- ...options?.hooks,
1011
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Hook object needs type assertion for field builder
1012
- } as any,
1013
- getZodSchema: (fieldName: string, operation: 'create' | 'update') => {
1014
- const validation = options?.validation
1015
- const isRequired = validation?.isRequired
1016
-
1017
- if (isRequired && operation === 'create') {
1018
- return z
1019
- .string({
1020
- message: `${formatFieldName(fieldName)} must be text`,
1021
- })
1022
- .min(1, {
1023
- message: `${formatFieldName(fieldName)} is required`,
1024
- })
1025
- } else if (isRequired && operation === 'update') {
1026
- return z
1027
- .string()
1028
- .min(1, {
1029
- message: `${formatFieldName(fieldName)} is required`,
1030
- })
1031
- .optional()
1032
- } else {
1033
- return z
1034
- .string({
1035
- message: `${formatFieldName(fieldName)} must be text`,
1036
- })
1037
- .optional()
1038
- .nullable()
1039
- }
1040
- },
1041
- getPrismaType: (_fieldName: string) => {
1042
- const validation = options?.validation
1043
- const db = options?.db
1044
- const isRequired = validation?.isRequired
1045
- const isNullable = db?.isNullable ?? !isRequired
1046
- let modifiers = ''
1047
-
1048
- if (isNullable) {
1049
- modifiers += '?'
1050
- }
1051
-
1052
- if (db?.nativeType) {
1053
- modifiers += ` @db.${db.nativeType}`
1054
- }
1055
-
1056
- if (db?.map) {
1057
- modifiers += ` @map("${db.map}")`
1058
- }
1059
-
1060
- return {
1061
- type: 'String',
1062
- modifiers: modifiers.trimStart() || undefined,
1063
- }
1064
- },
1065
- getTypeScriptType: () => {
1066
- const isRequired = options?.validation?.isRequired
1067
-
1068
- return {
1069
- type: 'string',
1070
- optional: !isRequired,
1071
- }
1072
- },
1073
- }
1074
- }
1075
-
1076
- /**
1077
- * Valid Prisma enum value pattern: starts with a letter, followed by letters, digits, or underscores
1078
- */
1079
- const PRISMA_ENUM_VALUE_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/
1080
-
1081
- /**
1082
- * Select field (enum-like)
1083
- */
1084
- export function select<
1085
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
1086
- >(options: Omit<SelectField<TTypeInfo>, 'type'>): SelectField<TTypeInfo> {
1087
- if (!options.options || options.options.length === 0) {
1088
- throw new Error('Select field must have at least one option')
1089
- }
1090
-
1091
- const isNativeEnum = options.db?.type === 'enum'
1092
-
1093
- if (isNativeEnum) {
1094
- const invalidValues = options.options
1095
- .map((opt) => opt.value)
1096
- .filter((value) => !PRISMA_ENUM_VALUE_PATTERN.test(value))
1097
-
1098
- if (invalidValues.length > 0) {
1099
- throw new Error(
1100
- `Enum select field values must be valid Prisma identifiers (letters, numbers, and underscores, starting with a letter). Invalid values: ${invalidValues.join(', ')}`,
1101
- )
1102
- }
1103
- }
1104
-
1105
- return {
1106
- type: 'select',
1107
- ...options,
1108
- getZodSchema: (fieldName: string, operation: 'create' | 'update') => {
1109
- const values = options.options.map((opt) => opt.value)
1110
- let schema: z.ZodTypeAny = z.enum(values as [string, ...string[]], {
1111
- message: `${formatFieldName(fieldName)} must be one of: ${values.join(', ')}`,
1112
- })
1113
-
1114
- if (!options.validation?.isRequired || operation === 'update') {
1115
- schema = schema.optional().nullable()
1116
- }
1117
-
1118
- return schema
1119
- },
1120
- getPrismaType: (fieldName: string, _provider?: string, listName?: string) => {
1121
- const isRequired = options.validation?.isRequired
1122
- const hasDefault = options.defaultValue !== undefined
1123
- // Nullability rules (Keystone parity):
1124
- // - `db.isNullable` is an explicit override and always wins. Setting it
1125
- // `true` forces the `?` even when a `defaultValue` is present.
1126
- // - Otherwise a select is nullable only when it is neither required nor
1127
- // carrying a default: a `defaultValue` makes the column NOT NULL (the
1128
- // long-standing default behaviour). This mirrors the previous logic
1129
- // where a present default overwrote the `?`.
1130
- // Nullability and the default are assembled independently with `+=`
1131
- // (mirroring text/integer) so the default never overwrites the `?`.
1132
- const isNullable = options.db?.isNullable ?? (!isRequired && !hasDefault)
1133
- let modifiers = ''
1134
-
1135
- if (isNullable) {
1136
- modifiers += '?'
1137
- }
1138
-
1139
- if (isNativeEnum) {
1140
- // Enum type name: explicit `db.enumName` wins, otherwise derive from
1141
- // list name + field name in PascalCase. The same name is used for the
1142
- // generated enum block (via `result.type`) and the column reference.
1143
- const capitalizedField = fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
1144
- const derivedEnumName = listName ? `${listName}${capitalizedField}` : capitalizedField
1145
- const enumName = options.db?.enumName ?? derivedEnumName
1146
-
1147
- // No quotes for enum default values (unlike the string branch below).
1148
- if (hasDefault) {
1149
- modifiers += ` @default(${options.defaultValue})`
1150
- }
1151
-
1152
- if (options.db?.map) {
1153
- modifiers += ` @map("${options.db.map}")`
1154
- }
1155
-
1156
- // Unique modifier — non-unique index routes through `index` below,
1157
- // same as `text()`'s getPrismaType.
1158
- if (options.isIndexed === 'unique') {
1159
- modifiers += ' @unique'
1160
- }
1161
-
1162
- return {
1163
- type: enumName,
1164
- modifiers: modifiers || undefined,
1165
- enumValues: options.options.map((opt) => opt.value),
1166
- index: options.isIndexed === true ? true : undefined,
1167
- }
1168
- }
1169
-
1170
- // String type (default)
1171
-
1172
- if (hasDefault) {
1173
- modifiers += ` @default("${options.defaultValue}")`
1174
- }
1175
-
1176
- if (options.db?.map) {
1177
- modifiers += ` @map("${options.db.map}")`
1178
- }
1179
-
1180
- if (options.isIndexed === 'unique') {
1181
- modifiers += ' @unique'
1182
- }
1183
-
1184
- return {
1185
- type: 'String',
1186
- modifiers: modifiers || undefined,
1187
- index: options.isIndexed === true ? true : undefined,
1188
- }
1189
- },
1190
- getTypeScriptType: () => {
1191
- // Generate union type from options (same for both string and enum db types)
1192
- const unionType = options.options.map((opt) => `'${opt.value}'`).join(' | ')
1193
-
1194
- return {
1195
- type: unionType,
1196
- optional: !options.validation?.isRequired || options.defaultValue !== undefined,
1197
- }
1198
- },
1199
- // Selects filter by equality against their enumerated options. The token
1200
- // value is matched (case-insensitively) against option value or label and
1201
- // resolved to the canonical stored value; an unknown option degrades to
1202
- // free text.
1203
- getFilterSpec: (fieldName: string): FilterSpec => ({
1204
- operators: ['eq'],
1205
- toCondition: (operator, value) => {
1206
- if (operator !== 'eq') return null
1207
- const needle = value.trim().toLowerCase()
1208
- const match = options.options.find(
1209
- (opt) => opt.value.toLowerCase() === needle || opt.label.toLowerCase() === needle,
1210
- )
1211
- if (!match) return null
1212
- return { [fieldName]: { equals: match.value } }
1213
- },
1214
- suggestions: {
1215
- valueSource: {
1216
- kind: 'enum',
1217
- options: options.options.map((opt) => ({ value: opt.value, label: opt.label })),
1218
- },
1219
- },
1220
- }),
1221
- }
1222
- }
1223
-
1224
- /**
1225
- * Parse a relationship ref into its target list and optional target field.
1226
- * Supports both 'ListName.fieldName' (bidirectional) and 'ListName' (list-only) formats.
1227
- */
1228
- function parseRelationshipRef(ref: string): { list: string; field?: string } {
1229
- const parts = ref.split('.')
1230
- if (parts.length === 1) {
1231
- const list = parts[0]
1232
- if (!list) {
1233
- throw new Error(`Invalid relationship ref: ${ref}`)
1234
- }
1235
- return { list }
1236
- } else if (parts.length === 2) {
1237
- const [list, field] = parts
1238
- if (!list || !field) {
1239
- throw new Error(`Invalid relationship ref: ${ref}`)
1240
- }
1241
- return { list, field }
1242
- } else {
1243
- throw new Error(`Invalid relationship ref: ${ref}`)
1244
- }
1245
- }
1246
-
1247
- function isOneToOneRelationship(
1248
- fieldName: string,
1249
- field: RelationshipField,
1250
- config: OpenSaasConfig,
1251
- ): boolean {
1252
- const { list: targetList, field: targetField } = parseRelationshipRef(field.ref)
1253
- if (!targetField) {
1254
- return false
1255
- }
1256
-
1257
- if (field.many) {
1258
- return false
1259
- }
1260
-
1261
- const targetListConfig = config.lists[targetList]
1262
- if (!targetListConfig) {
1263
- throw new Error(`Referenced list "${targetList}" not found in config`)
1264
- }
1265
-
1266
- const targetFieldConfig = targetListConfig.fields[targetField]
1267
- if (!targetFieldConfig) {
1268
- throw new Error(
1269
- `Referenced field "${targetList}.${targetField}" not found. If you want a one-sided relationship, use ref: "${targetList}" instead of ref: "${targetList}.${targetField}"`,
1270
- )
1271
- }
1272
- if (targetFieldConfig.type !== 'relationship') {
1273
- throw new Error(`Referenced field "${targetList}.${targetField}" is not a relationship field`)
1274
- }
1275
-
1276
- return !(targetFieldConfig as RelationshipField).many
1277
- }
1278
-
1279
- function shouldHaveForeignKey(
1280
- listKey: string,
1281
- fieldName: string,
1282
- field: RelationshipField,
1283
- config: OpenSaasConfig,
1284
- ): boolean {
1285
- const { list: targetList, field: targetField } = parseRelationshipRef(field.ref)
1286
- if (!targetField) {
1287
- return true
1288
- }
1289
-
1290
- if (field.many) {
1291
- return false
1292
- }
1293
-
1294
- const isOneToOne = isOneToOneRelationship(fieldName, field, config)
1295
- if (!isOneToOne) {
1296
- return true
1297
- }
1298
-
1299
- const targetListConfig = config.lists[targetList]!
1300
- const targetFieldConfig = targetListConfig.fields[targetField] as RelationshipField
1301
-
1302
- const thisSideExplicit = field.db?.foreignKey
1303
- const otherSideExplicit = targetFieldConfig.db?.foreignKey
1304
-
1305
- if (thisSideExplicit === true && otherSideExplicit === true) {
1306
- throw new Error(
1307
- `Invalid one-to-one relationship: both "${listKey}.${fieldName}" and "${targetList}.${targetField}" have db.foreignKey set to true. Only one side can store the foreign key.`,
1308
- )
1309
- }
1310
-
1311
- if (thisSideExplicit === true) {
1312
- return true
1313
- }
1314
-
1315
- if (otherSideExplicit === true) {
1316
- return false
1317
- }
1318
-
1319
- // Default: the alphabetically "smaller" list name gets the foreign key
1320
- const comparison = listKey.localeCompare(targetList)
1321
- if (comparison !== 0) {
1322
- return comparison < 0
1323
- }
1324
-
1325
- // Self-referential: use field name ordering
1326
- return fieldName.localeCompare(targetField) < 0
1327
- }
1328
-
1329
- function isManyToMany(
1330
- fieldName: string,
1331
- field: RelationshipField,
1332
- config: OpenSaasConfig,
1333
- ): boolean {
1334
- if (!field.many) {
1335
- return false
1336
- }
1337
-
1338
- const { list: targetList, field: targetField } = parseRelationshipRef(field.ref)
1339
-
1340
- // List-only ref with many: true is implicitly many-to-many
1341
- if (!targetField) {
1342
- return true
1343
- }
1344
-
1345
- const targetFieldConfig = config.lists[targetList]?.fields[targetField]
1346
- if (!targetFieldConfig || targetFieldConfig.type !== 'relationship') {
1347
- return false
1348
- }
1349
-
1350
- return !!(targetFieldConfig as RelationshipField).many
1351
- }
1352
-
1353
- /**
1354
- * Compute the explicit relation name for a bidirectional many-to-many relationship,
1355
- * or `undefined` when Prisma's default naming should be used.
1356
- *
1357
- * Honours per-field `db.relationName` (which must match on both sides) and the
1358
- * global `db.joinTableNaming: 'keystone'` setting, picking a deterministic owner
1359
- * for bidirectional relationships so both sides resolve to the same name.
1360
- */
1361
- function computeManyToManyRelationName(
1362
- listKey: string,
1363
- fieldName: string,
1364
- field: RelationshipField,
1365
- config: OpenSaasConfig,
1366
- ): string | undefined {
1367
- const { list: targetList, field: targetField } = parseRelationshipRef(field.ref)
1368
- const joinTableNaming = config.db.joinTableNaming || 'prisma'
1369
-
1370
- const sourceRelationName = field.db?.relationName
1371
- let targetRelationName: string | undefined
1372
- if (targetField) {
1373
- const targetFieldConfig = config.lists[targetList]?.fields[targetField]
1374
- if (targetFieldConfig?.type === 'relationship') {
1375
- targetRelationName = (targetFieldConfig as RelationshipField).db?.relationName
1376
- }
1377
- }
1378
-
1379
- if (sourceRelationName && targetRelationName && sourceRelationName !== targetRelationName) {
1380
- throw new Error(
1381
- `Relation name mismatch: ${listKey}.${fieldName} has relationName "${sourceRelationName}" but ${targetList}.${targetField} has "${targetRelationName}". Both sides must use the same relationName.`,
1382
- )
1383
- }
1384
-
1385
- const explicitRelationName = sourceRelationName || targetRelationName
1386
- if (explicitRelationName) {
1387
- return explicitRelationName
1388
- }
1389
-
1390
- if (joinTableNaming === 'keystone') {
1391
- if (targetField) {
1392
- // Pick a deterministic owner so both sides agree on the relation name
1393
- const sourceKey = `${listKey}.${fieldName}`
1394
- const targetKey = `${targetList}.${targetField}`
1395
- return sourceKey.localeCompare(targetKey) < 0
1396
- ? `${listKey}_${fieldName}`
1397
- : `${targetList}_${targetField}`
1398
- }
1399
- return `${listKey}_${fieldName}`
1400
- }
1401
-
1402
- return undefined
1403
- }
1404
-
1405
- /**
1406
- * The name Prisma generation synthesizes for the back-relation a list-only
1407
- * `ref` (`ref: 'ListName'`, no target field) creates on its target model —
1408
- * Prisma requires an opposite field, and the config never declares one.
1409
- * Exported so runtime nested-write resolution (`resolveSyntheticReverseRelation`
1410
- * in `access/engine.ts`) can recognise the same name rather than re-deriving
1411
- * the format by string parsing (#978).
1412
- */
1413
- export function getSyntheticFieldName(listKey: string, fieldName: string): string {
1414
- return `from_${listKey}_${fieldName}`
1415
- }
1416
-
1417
- function getPrismaRelation(
1418
- field: RelationshipField,
1419
- fieldName: string,
1420
- listKey: string,
1421
- config: OpenSaasConfig,
1422
- ): PrismaRelationResult {
1423
- const { list: targetList, field: targetField } = parseRelationshipRef(field.ref)
1424
- const paddedName = fieldName.padEnd(12)
1425
-
1426
- // Synthetic back-relation for list-only refs (Prisma requires an opposite field)
1427
- let backRelation: PrismaRelationResult['backRelation']
1428
- if (!targetField) {
1429
- const syntheticFieldName = getSyntheticFieldName(listKey, fieldName)
1430
- const relationName = field.db?.relationName ?? `${listKey}_${fieldName}`
1431
- backRelation = {
1432
- targetList,
1433
- line: ` ${syntheticFieldName.padEnd(12)} ${listKey}[] @relation("${relationName}")`,
1434
- }
1435
- }
1436
-
1437
- if (field.many) {
1438
- let relationLine: string
1439
-
1440
- if (targetField) {
1441
- // Bidirectional many side: use explicit relation name only for true many-to-many
1442
- const m2mName = isManyToMany(fieldName, field, config)
1443
- ? computeManyToManyRelationName(listKey, fieldName, field, config)
1444
- : undefined
1445
- relationLine = m2mName
1446
- ? ` ${paddedName} ${targetList}[] @relation("${m2mName}")`
1447
- : ` ${paddedName} ${targetList}[]`
1448
- } else {
1449
- // List-only ref many side: always a named relation paired with the synthetic field
1450
- const relationName = field.db?.relationName ?? `${listKey}_${fieldName}`
1451
- relationLine = ` ${paddedName} ${targetList}[] @relation("${relationName}")`
1452
- }
1453
-
1454
- if (field.db?.extendPrismaSchema) {
1455
- relationLine = field.db.extendPrismaSchema({ relationLine }).relationLine
1456
- }
1457
-
1458
- return { modelLines: [relationLine], backRelation }
1459
- }
1460
-
1461
- // Single relationship
1462
- if (shouldHaveForeignKey(listKey, fieldName, field, config)) {
1463
- const foreignKeyField = `${fieldName}Id`
1464
- const fkPaddedName = foreignKeyField.padEnd(12)
1465
-
1466
- const uniqueModifier = isOneToOneRelationship(fieldName, field, config) ? ' @unique' : ''
1467
-
1468
- const mapModifier =
1469
- typeof field.db?.foreignKey === 'object' && field.db.foreignKey.map
1470
- ? ` @map("${field.db.foreignKey.map}")`
1471
- : ` @map("${fieldName}")`
1472
-
1473
- // Nullability: explicit db.isNullable overrides the default (nullable),
1474
- // matching the scalar fields' `db.isNullable` convention. It moves the FK
1475
- // column and its relation field together — they can never disagree.
1476
- const isNullable = field.db?.isNullable ?? true
1477
- const nullModifier = isNullable ? '?' : ''
1478
-
1479
- let fkLine = ` ${fkPaddedName} String${nullModifier}${uniqueModifier}${mapModifier}`
1480
- let relationLine = targetField
1481
- ? ` ${paddedName} ${targetList}${nullModifier} @relation(fields: [${foreignKeyField}], references: [id])`
1482
- : ` ${paddedName} ${targetList}${nullModifier} @relation("${listKey}_${fieldName}", fields: [${foreignKeyField}], references: [id])`
1483
-
1484
- if (field.db?.extendPrismaSchema) {
1485
- const extended = field.db.extendPrismaSchema({ fkLine, relationLine })
1486
- fkLine = extended.fkLine ?? fkLine
1487
- relationLine = extended.relationLine
1488
- }
1489
-
1490
- // Default to indexing foreign keys (matching Keystone behaviour) unless disabled
1491
- const indexType = field.isIndexed ?? true
1492
- const foreignKeyIndex = indexType !== false ? { foreignKeyField, indexType } : undefined
1493
-
1494
- return { modelLines: [fkLine, relationLine], foreignKeyField, foreignKeyIndex, backRelation }
1495
- }
1496
-
1497
- // Non-FK side of a one-to-one relationship: just the relation field. This
1498
- // side has no foreign key column, so `db.isNullable` (which only makes
1499
- // sense paired with a column) cannot be honoured here — reject rather than
1500
- // silently ignore a developer's stated intent (the FK-owning side is
1501
- // determined by `db.foreignKey`/alphabetical ordering, not by which field
1502
- // declares `isNullable`).
1503
- if (field.db?.isNullable === false) {
1504
- throw new Error(
1505
- `db.isNullable can only be used on the foreign-key-owning side of a relationship. ` +
1506
- `"${listKey}.${fieldName}" does not own the foreign key for this one-to-one relationship — ` +
1507
- `set db.isNullable on "${targetList}.${targetField}" instead, or make this side own the ` +
1508
- `foreign key via db.foreignKey.`,
1509
- )
1510
- }
1511
-
1512
- let relationLine = ` ${paddedName} ${targetList}?`
1513
- if (field.db?.extendPrismaSchema) {
1514
- relationLine = field.db.extendPrismaSchema({ relationLine }).relationLine
1515
- }
1516
-
1517
- return { modelLines: [relationLine], backRelation }
1518
- }
1519
-
1520
- /**
1521
- * Relationship field
1522
- */
1523
- export function relationship<
1524
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
1525
- >(options: Omit<RelationshipField<TTypeInfo>, 'type'>): RelationshipField<TTypeInfo> {
1526
- if (!options.ref) {
1527
- throw new Error('Relationship field must have a ref')
1528
- }
1529
-
1530
- const refParts = options.ref.split('.')
1531
- if (refParts.length !== 1 && refParts.length !== 2) {
1532
- throw new Error(
1533
- `Invalid relationship ref format: "${options.ref}". Expected format: "ListName.fieldName" or "ListName"`,
1534
- )
1535
- }
1536
-
1537
- if (options.db?.foreignKey !== undefined) {
1538
- if (options.many) {
1539
- throw new Error(
1540
- 'db.foreignKey can only be used on single relationships (many: false or undefined). ' +
1541
- 'Many-side of a relationship never stores the foreign key.',
1542
- )
1543
- }
1544
-
1545
- if (refParts.length === 1 && typeof options.db.foreignKey === 'boolean') {
1546
- throw new Error(
1547
- 'db.foreignKey cannot be a boolean on list-only refs (ref: "ListName"). ' +
1548
- 'List-only refs always create foreign keys automatically, so the ownership sense of ' +
1549
- 'db.foreignKey is meaningless here. Use db.foreignKey: { map: "columnName" } to rename ' +
1550
- 'the foreign key column instead.',
1551
- )
1552
- }
1553
- }
1554
-
1555
- if (options.db?.isNullable !== undefined && options.many) {
1556
- throw new Error(
1557
- 'db.isNullable can only be used on single relationships (many: false or undefined). ' +
1558
- 'Many-side of a relationship has no foreign key column to make non-nullable.',
1559
- )
1560
- }
1561
-
1562
- const field: RelationshipField<TTypeInfo> = {
1563
- type: 'relationship',
1564
- ...options,
1565
- }
1566
-
1567
- field.getPrismaRelation = (
1568
- fieldName: string,
1569
- _allFields: Record<string, FieldConfig>,
1570
- listKey: string,
1571
- config: OpenSaasConfig,
1572
- ) => getPrismaRelation(field as RelationshipField, fieldName, listKey, config)
1573
-
1574
- // Relationships filter differently by cardinality (issue #732):
1575
- // • to-one filters by the related Item's label — `author:"Ada Lovelace"`
1576
- // becomes a nested `is` `contains` on the target list's Label field.
1577
- // • to-many filters by the access-visible related COUNT with numeric
1578
- // comparisons — `orders:>5`. Prisma cannot compare a relation count in a
1579
- // `where`, so the mapper emits a structured count marker
1580
- // (RELATIONSHIP_COUNT_FILTER_KEY) that `resolveRelationshipCountFilters`
1581
- // later turns into an access-scoped `{ id: { in } }`.
1582
- // The mapper stays pure in both cases (no DB lookup). Suggestions point a
1583
- // to-one at the target list's label lookup; a to-many exposes no value source
1584
- // (a numeric compare, like an integer field).
1585
- field.getFilterSpec = (
1586
- _fieldName: string,
1587
- _listKey: string,
1588
- config: OpenSaasConfig,
1589
- ): FilterSpec | undefined => {
1590
- const { list: targetList } = parseRelationshipRef(field.ref)
1591
- const relatedListConfig = config.lists[targetList]
1592
- if (!relatedListConfig) return undefined
1593
-
1594
- if (field.many === true) {
1595
- return {
1596
- operators: COMPARISON_OPERATORS,
1597
- toCondition: (operator, value) => {
1598
- const trimmed = value.trim()
1599
- // A non-integer count comparison can't be interpreted → degrade to
1600
- // free text (matching the integer field's behaviour).
1601
- if (!/^-?\d+$/.test(trimmed)) return null
1602
- return {
1603
- [_fieldName]: { [RELATIONSHIP_COUNT_FILTER_KEY]: { operator, value: Number(trimmed) } },
1604
- }
1605
- },
1606
- suggestions: { valueSource: { kind: 'none' } },
1607
- }
1608
- }
1609
-
1610
- const labelField = getLabelFieldName(relatedListConfig)
1611
- const labelFieldConfig = relatedListConfig.fields[labelField]
1612
- // A virtual label field has no queryable column, so `contains` can't run
1613
- // against it — the relationship is then not filterable.
1614
- if (labelFieldConfig?.virtual === true) return undefined
1615
-
1616
- return {
1617
- operators: ['eq'],
1618
- toCondition: (operator, value) => {
1619
- if (operator !== 'eq') return null
1620
- return { [_fieldName]: { is: { [labelField]: { contains: value } } } }
1621
- },
1622
- suggestions: { valueSource: { kind: 'relationship', listKey: targetList, many: false } },
1623
- }
1624
- }
1625
-
1626
- return field
1627
- }
1628
-
1629
- /**
1630
- * JSON field for storing arbitrary JSON data
1631
- *
1632
- * **Features:**
1633
- * - Stores any valid JSON data (objects, arrays, primitives)
1634
- * - Stored as JSON type in database (PostgreSQL/MySQL) or TEXT in SQLite
1635
- * - Optional validation for required fields
1636
- * - UI options for formatting and display
1637
- *
1638
- * **Usage Example:**
1639
- * ```typescript
1640
- * // In opensaas.config.ts
1641
- * fields: {
1642
- * metadata: json({
1643
- * validation: { isRequired: false },
1644
- * ui: {
1645
- * placeholder: 'Enter JSON data...',
1646
- * rows: 10,
1647
- * formatted: true
1648
- * }
1649
- * }),
1650
- * settings: json({
1651
- * validation: { isRequired: true }
1652
- * })
1653
- * }
1654
- *
1655
- * // Creating with JSON data
1656
- * const item = await context.db.item.create({
1657
- * data: {
1658
- * metadata: { key: 'value', nested: { data: [1, 2, 3] } }
1659
- * }
1660
- * })
1661
- *
1662
- * // Querying returns parsed JSON
1663
- * const item = await context.db.item.findUnique({
1664
- * where: { id: '...' }
1665
- * })
1666
- * console.log(item.metadata.key) // 'value'
1667
- * ```
1668
- *
1669
- * @param options - Field configuration options
1670
- * @returns JSON field configuration
1671
- */
1672
- export function json<
1673
- TTypeInfo extends import('../config/types.js').TypeInfo = import('../config/types.js').TypeInfo,
1674
- >(options?: Omit<JsonField<TTypeInfo>, 'type'>): JsonField<TTypeInfo> {
1675
- return {
1676
- type: 'json',
1677
- ...options,
1678
- getZodSchema: (fieldName: string, operation: 'create' | 'update') => {
1679
- const validation = options?.validation
1680
- const isRequired = validation?.isRequired
1681
-
1682
- const baseSchema = z.unknown()
1683
-
1684
- if (isRequired && operation === 'create') {
1685
- // Required in create mode: a value must be provided and it must be
1686
- // non-null (issue #604 — a required json field means non-null). A bare
1687
- // z.unknown() is treated as optional inside z.object(), so an omitted
1688
- // key would silently pass; the refinement makes the key genuinely
1689
- // required by rejecting undefined (which also covers an absent key) and
1690
- // rejecting a present null, while still accepting any other present
1691
- // JSON value (object, array, primitive, including falsy 0/""/false).
1692
- return baseSchema.refine((value) => value !== undefined && value !== null, {
1693
- message: `${formatFieldName(fieldName)} is required`,
1694
- })
1695
- } else if (isRequired && operation === 'update') {
1696
- // Required in update mode: omitted keys still pass (issue #570 — partial
1697
- // updates may leave the field untouched), but a present null is rejected
1698
- // (issue #604 — required json means non-null). The `.refine()` runs
1699
- // before `.optional()` short-circuits on undefined: absent/undefined
1700
- // passes, a present null is rejected, and other present values pass.
1701
- return baseSchema
1702
- .refine((value) => value !== null, {
1703
- message: `${formatFieldName(fieldName)} is required`,
1704
- })
1705
- .optional()
1706
- } else {
1707
- return baseSchema.optional().nullable()
1708
- }
1709
- },
1710
- getPrismaType: (_fieldName: string) => {
1711
- const validation = options?.validation
1712
- const db = options?.db
1713
- const isRequired = validation?.isRequired
1714
- const isNullable = db?.isNullable ?? !isRequired
1715
- let modifiers = ''
1716
-
1717
- if (isNullable) {
1718
- modifiers += '?'
1719
- }
1720
-
1721
- if (db?.nativeType) {
1722
- modifiers += ` @db.${db.nativeType}`
1723
- }
1724
-
1725
- const defaultLiteral = formatPrismaDefault(options?.defaultValue, 'json')
1726
- if (defaultLiteral !== undefined) {
1727
- modifiers += ` @default(${defaultLiteral})`
1728
- }
1729
-
1730
- if (db?.map) {
1731
- modifiers += ` @map("${db.map}")`
1732
- }
1733
-
1734
- return {
1735
- type: 'Json',
1736
- modifiers: modifiers.trimStart() || undefined,
1737
- }
1738
- },
1739
- getTypeScriptType: () => {
1740
- const isRequired = options?.validation?.isRequired
1741
-
1742
- return {
1743
- type: 'unknown',
1744
- optional: !isRequired,
1745
- }
1746
- },
1747
- }
1748
- }
1749
-
1750
- /**
1751
- * Convert a TypeDescriptor to a TypeScript type string
1752
- * Handles three formats:
1753
- * 1. Primitive string: 'string', 'number', 'boolean' -> returned as-is
1754
- * 2. Import string: "import('decimal.js').Decimal" -> returned as-is
1755
- * 3. Type object: { value: Decimal, from: 'decimal.js' } -> "import('decimal.js').Decimal"
1756
- */
1757
- function typeDescriptorToString(descriptor: import('../config/types.js').TypeDescriptor): string {
1758
- if (typeof descriptor === 'string') {
1759
- return descriptor
1760
- }
1761
-
1762
- const typeName = descriptor.name || descriptor.value.name
1763
-
1764
- return `import('${descriptor.from}').${typeName}`
1765
- }
1766
-
1767
- function typeDescriptorToImports(
1768
- descriptor: import('../config/types.js').TypeDescriptor,
1769
- ): Array<{ names: string[]; from: string; typeOnly?: boolean }> {
1770
- if (typeof descriptor === 'string') {
1771
- const importMatch = descriptor.match(/import\('([^']+)'\)\.(\w+)/)
1772
- if (importMatch) {
1773
- return [
1774
- {
1775
- names: [importMatch[2]],
1776
- from: importMatch[1],
1777
- typeOnly: true,
1778
- },
1779
- ]
1780
- }
1781
- return []
1782
- }
1783
-
1784
- // Type object descriptor
1785
- const typeName = descriptor.name || descriptor.value.name
1786
- return [
1787
- {
1788
- names: [typeName],
1789
- from: descriptor.from,
1790
- typeOnly: true,
1791
- },
1792
- ]
1793
- }
1794
-
1795
- /**
1796
- * Virtual field - not stored in database, computed via hooks
1797
- *
1798
- * **Features:**
1799
- * - Does not create a column in the database
1800
- * - Uses resolveOutput hook to compute value from other fields
1801
- * - Optionally uses resolveInput hook for write side effects (e.g., sync to external API)
1802
- * - Only computed when explicitly selected/included in queries
1803
- * - Supports both read and write operations via hooks
1804
- * - Supports custom scalar types (e.g., Decimal) for financial precision
1805
- *
1806
- * **Usage Examples:**
1807
- * ```typescript
1808
- * // Read-only computed field with primitive type
1809
- * fields: {
1810
- * firstName: text(),
1811
- * lastName: text(),
1812
- * fullName: virtual({
1813
- * type: 'string',
1814
- * hooks: {
1815
- * resolveOutput: ({ item }) => `${item.firstName} ${item.lastName}`
1816
- * }
1817
- * })
1818
- * }
1819
- *
1820
- * // Custom scalar type using import string
1821
- * fields: {
1822
- * totalPrice: virtual({
1823
- * type: "import('decimal.js').Decimal",
1824
- * hooks: {
1825
- * resolveOutput: ({ item }) => new Decimal(item.price).times(item.quantity)
1826
- * }
1827
- * })
1828
- * }
1829
- *
1830
- * // Custom scalar type using type descriptor (recommended)
1831
- * import Decimal from 'decimal.js'
1832
- *
1833
- * fields: {
1834
- * totalPrice: virtual({
1835
- * type: { value: Decimal, from: 'decimal.js' },
1836
- * hooks: {
1837
- * resolveOutput: ({ item }) => new Decimal(item.price).times(item.quantity)
1838
- * }
1839
- * })
1840
- * }
1841
- *
1842
- * // Write side effects (e.g., sync to external API)
1843
- * fields: {
1844
- * externalSync: virtual({
1845
- * type: 'boolean',
1846
- * hooks: {
1847
- * resolveInput: async ({ item }) => {
1848
- * await syncToExternalAPI(item)
1849
- * return undefined // Don't store anything
1850
- * },
1851
- * resolveOutput: () => true
1852
- * }
1853
- * })
1854
- * }
1855
- * ```
1856
- *
1857
- * **Requirements:**
1858
- * - Must provide `type` (TypeScript type string, import string, or type descriptor)
1859
- * - Must provide `resolveOutput` hook (for reads)
1860
- * - Optional `resolveInput` hook (for write side effects)
1861
- *
1862
- * @param options - Virtual field configuration
1863
- * @returns Virtual field configuration
1864
- */
1865
- export function virtual<TTypeInfo extends import('../config/types.js').TypeInfo>(
1866
- options: Omit<VirtualField<TTypeInfo>, 'virtual' | 'outputType' | 'type'> & {
1867
- type: import('../config/types.js').TypeDescriptor
1868
- },
1869
- ): VirtualField<TTypeInfo> {
1870
- if (!options.hooks?.resolveOutput) {
1871
- throw new Error(
1872
- 'Virtual fields must provide a resolveOutput hook to compute their value. ' +
1873
- 'Example: hooks: { resolveOutput: ({ item }) => computeValue(item) }',
1874
- )
1875
- }
1876
-
1877
- const outputType = typeDescriptorToString(options.type)
1878
- const imports = typeDescriptorToImports(options.type)
1879
-
1880
- const { type: _, ...rest } = options
1881
-
1882
- return {
1883
- type: 'virtual',
1884
- virtual: true,
1885
- outputType,
1886
- ...rest,
1887
- // undefined signals the generator to skip creating a database column.
1888
- getPrismaType: undefined,
1889
- getTypeScriptType: () => {
1890
- return {
1891
- type: outputType,
1892
- optional: false, // A virtual field always computes a value.
1893
- }
1894
- },
1895
- getTypeScriptImports: imports.length > 0 ? () => imports : undefined,
1896
- // Virtual fields don't accept database input, so validation always fails.
1897
- getZodSchema: () => {
1898
- return z.never()
1899
- },
1900
- }
1901
- }