viborm 1.14.2 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +15 -3
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
  6. package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
  7. package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
  8. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +2 -2
  18. package/dist/cache.mjs +1 -1
  19. package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
  20. package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
  21. package/dist/cli.mjs +2 -2
  22. package/dist/cli.mjs.map +1 -1
  23. package/dist/client-CVCC-D1j.mjs +2 -0
  24. package/dist/client-CVCC-D1j.mjs.map +1 -0
  25. package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
  26. package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
  27. package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
  28. package/dist/client.d.mts +3 -3
  29. package/dist/client.mjs +1 -1
  30. package/dist/config.d.mts +1 -1
  31. package/dist/config.mjs +1 -1
  32. package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
  33. package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
  34. package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
  35. package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
  36. package/dist/d1.d.mts +1 -1
  37. package/dist/d1.mjs +1 -1
  38. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
  39. package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
  40. package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
  41. package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
  42. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
  43. package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
  44. package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
  45. package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
  46. package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
  47. package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
  48. package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
  49. package/dist/driver.d.mts +1 -1
  50. package/dist/driver.mjs +1 -1
  51. package/dist/durable-object.d.mts +1 -1
  52. package/dist/durable-object.mjs +1 -1
  53. package/dist/error-mapping-DIRlrmDK.mjs +2 -0
  54. package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
  55. package/dist/every-BHEmfLOW.mjs +2 -0
  56. package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
  57. package/dist/execution-context-VMQm-9CH.mjs +2 -0
  58. package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
  59. package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
  60. package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
  61. package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
  62. package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
  63. package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
  64. package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
  65. package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
  66. package/dist/identifiers-BTCfD5ic.mjs +2 -0
  67. package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
  68. package/dist/index.d.mts +2 -2
  69. package/dist/index.mjs +1 -1
  70. package/dist/instrumentation.d.mts +1 -1
  71. package/dist/instrumentation.mjs +1 -1
  72. package/dist/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
  73. package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
  74. package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
  75. package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
  76. package/dist/judge-words-DpwxOfre.mjs +2 -0
  77. package/dist/judge-words-DpwxOfre.mjs.map +1 -0
  78. package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
  79. package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
  80. package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
  81. package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
  82. package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
  83. package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
  84. package/dist/libsql.d.mts +1 -1
  85. package/dist/libsql.mjs +1 -1
  86. package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
  87. package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
  88. package/dist/methods-part-DoTrY6b9.mjs +2 -0
  89. package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
  90. package/dist/migrations/mysql.d.mts +4 -4
  91. package/dist/migrations/mysql.mjs +1 -1
  92. package/dist/migrations/postgres.d.mts +4 -4
  93. package/dist/migrations/postgres.mjs +1 -1
  94. package/dist/migrations/snowflake.d.mts +4 -4
  95. package/dist/migrations/snowflake.mjs +1 -1
  96. package/dist/migrations/sqlite.d.mts +4 -4
  97. package/dist/migrations/sqlite.mjs +1 -1
  98. package/dist/migrations/storage/durable-object.mjs +1 -1
  99. package/dist/migrations/storage/r2.mjs +1 -1
  100. package/dist/migrations/surrealdb.d.mts +4 -4
  101. package/dist/migrations/surrealdb.mjs +1 -1
  102. package/dist/migrations/tenant.d.mts +2 -2
  103. package/dist/migrations/tenant.mjs +1 -1
  104. package/dist/migrations.d.mts +4 -4
  105. package/dist/migrations.mjs +1 -1
  106. package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
  107. package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
  108. package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
  109. package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
  110. package/dist/mysql2.d.mts +1 -1
  111. package/dist/mysql2.mjs +1 -1
  112. package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
  113. package/dist/named-statements-CMj1QEyw.mjs +2 -0
  114. package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
  115. package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
  116. package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
  117. package/dist/neon-http.d.mts +1 -1
  118. package/dist/neon-http.mjs +1 -1
  119. package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
  120. package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
  121. package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
  122. package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
  123. package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
  124. package/dist/on.d.mts +1 -1
  125. package/dist/on.mjs +1 -1
  126. package/dist/ordering/keys.mjs +1 -1
  127. package/dist/ordering.d.mts +1 -1
  128. package/dist/ordering.mjs +1 -1
  129. package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
  130. package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
  131. package/dist/permissions.d.mts +1 -1
  132. package/dist/permissions.mjs +1 -1
  133. package/dist/pg.d.mts +27 -1
  134. package/dist/pg.mjs +1 -1
  135. package/dist/pg.mjs.map +1 -1
  136. package/dist/pglite.d.mts +1 -1
  137. package/dist/pglite.mjs +1 -1
  138. package/dist/{physical-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
  139. package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
  140. package/dist/planetscale.d.mts +1 -1
  141. package/dist/planetscale.mjs +1 -1
  142. package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
  143. package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
  144. package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
  145. package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
  146. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
  147. package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
  148. package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
  149. package/dist/postgres-result-CiS5OWp1.mjs +2 -0
  150. package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
  151. package/dist/postgres.d.mts +17 -1
  152. package/dist/postgres.mjs +1 -1
  153. package/dist/postgres.mjs.map +1 -1
  154. package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
  155. package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
  156. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
  157. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
  158. package/dist/query-Cdy8E2jM.mjs +2 -0
  159. package/dist/query-Cdy8E2jM.mjs.map +1 -0
  160. package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
  161. package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
  162. package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
  163. package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
  164. package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
  165. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
  166. package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
  167. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
  168. package/dist/scalar-B9WizsvR.mjs +4 -0
  169. package/dist/scalar-B9WizsvR.mjs.map +1 -0
  170. package/dist/schema/introspect.d.mts +2 -2
  171. package/dist/schema/introspect.mjs +1 -1
  172. package/dist/schema/json.d.mts +2 -2
  173. package/dist/schema/json.mjs +1 -1
  174. package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
  175. package/dist/schema-MB-pPNTO.mjs.map +1 -0
  176. package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
  177. package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
  178. package/dist/schema-introspection-wMVZowIF.mjs +6 -0
  179. package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
  180. package/dist/schema.d.mts +1 -1
  181. package/dist/schema.mjs +1 -1
  182. package/dist/select-assembly-SuVxJjps.mjs +2 -0
  183. package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
  184. package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
  185. package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
  186. package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
  187. package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
  188. package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
  189. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
  190. package/dist/snowflake.d.mts +2 -2
  191. package/dist/snowflake.mjs +1 -1
  192. package/dist/snowflake.mjs.map +1 -1
  193. package/dist/soft-delete.d.mts +1 -1
  194. package/dist/soft-delete.mjs +1 -1
  195. package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
  196. package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
  197. package/dist/sql-BGjAsoBE.mjs +2 -0
  198. package/dist/sql-BGjAsoBE.mjs.map +1 -0
  199. package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
  200. package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
  201. package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
  202. package/dist/sql.d.mts +1 -1
  203. package/dist/sql.mjs +1 -1
  204. package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
  205. package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
  206. package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
  207. package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
  208. package/dist/sqlite3.d.mts +1 -1
  209. package/dist/sqlite3.mjs +1 -1
  210. package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
  211. package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
  212. package/dist/surrealdb.d.mts +2 -2
  213. package/dist/surrealdb.mjs +1 -1
  214. package/dist/surrealdb.mjs.map +1 -1
  215. package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
  216. package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
  217. package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
  218. package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
  219. package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
  220. package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
  221. package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
  222. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
  223. package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
  224. package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
  225. package/dist/validation-D0LG854o.mjs +2 -0
  226. package/dist/validation-D0LG854o.mjs.map +1 -0
  227. package/dist/validation.d.mts +1 -1
  228. package/dist/validation.mjs +1 -1
  229. package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
  230. package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
  231. package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
  232. package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
  233. package/dist/version-B_ZLWzLW.mjs +2 -0
  234. package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
  235. package/package.json +35 -35
  236. package/dist/client-DRpX3-vw.mjs +0 -2
  237. package/dist/client-DRpX3-vw.mjs.map +0 -1
  238. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  239. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  240. package/dist/every-tOgQmaIE.mjs +0 -2
  241. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  242. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  243. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  244. package/dist/identifiers-s00pGES8.mjs +0 -2
  245. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  246. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  247. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  248. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  249. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  250. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  251. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  252. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  253. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  254. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  255. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  256. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  257. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  258. package/dist/query-BZVHfA0s.mjs +0 -2
  259. package/dist/query-BZVHfA0s.mjs.map +0 -1
  260. package/dist/scalar-BHCh7aUz.mjs +0 -4
  261. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  262. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  263. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  264. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  265. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  266. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  267. package/dist/sql-3o4DOKm9.mjs +0 -2
  268. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  269. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  270. package/dist/validation-CYaJ8ndO.mjs +0 -2
  271. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  272. package/dist/version-CXGIA82S.mjs +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"judge-words-CzUyXtJ6.mjs","names":["own","listed","given","lazy","sql","sql","sql","holds","sql","sql","judgedHolds","placed","own","given","lazy","facts","own","Kept","gate","own","given","gate","holds","facts","lazy","own","own","given","lazy","at"],"sources":["../src/extensions/entries.ts","../src/adapters/databases/mysql/judged.ts","../src/adapters/databases/postgres/judged.ts","../src/adapters/databases/sqlite/judged.ts","../src/adapters/judged.ts","../src/extensions/reads.ts","../src/extensions/produced.ts","../src/extensions/judge.ts","../src/extensions/admission.ts","../src/extensions/rows.ts","../src/extensions/kept.ts","../src/extensions/gates.ts","../src/extensions/projected.ts","../src/extensions/projection.ts","../src/extensions/rule.ts","../src/extensions/judge-words.ts"],"sourcesContent":["/**\n * What a rule holds beyond its filters, brought by the words that write it\n * (`only`, `check`, `gate`, `facts`, `lazy`), so a rule that only filters\n * holds none of this code: per model and layer, which rows a write may take\n * (`update`, `delete`, `writes`), what the rows it produces must hold and\n * what a read carries or hides, admitted once per schema and bound once per\n * application as the engine reads them (`JudgedEntry`). What judges and what\n * projects come with the words that ask for them; for an entry given lazily,\n * whose words are known only once its model is read, a forwarder asks the\n * model first.\n */\nimport type { Queries } from \"@query-engine/raptor3/shared/query\";\nimport type {\n JudgedEntry,\n LazyRelations,\n WriteJudgement,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport { type Input, memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport type {\n Admission,\n AdmittedEntry,\n BoundEntries,\n EntryDraft,\n EntryHost,\n References,\n RuleLayer,\n} from \"./admission\";\nimport type { ResolvedExtensionChain } from \"./chain-state\";\nimport { FilterDomain, preparer } from \"./row-domain\";\nimport type { Site } from \"./rule-words\";\n\n/** No restriction: what a key an entry leaves out takes, read as no predicate. */\nexport const ALL: Input = Object.freeze({});\n\n/** Whether a predicate an entry may leave out is given. */\nexport const given = (input: Input | undefined): input is Input =>\n input !== undefined;\n\n/**\n * The predicates one layer's entry gives a write `judgement`, each once:\n * `delete`'s, or per field an update writes that field's own, else\n * `update`'s, or `update`'s when it writes none (R3).\n */\nexport function judgedInputs(\n entry: JudgedEntry,\n judgement: WriteJudgement\n): Input[] {\n const { update = ALL, delete: removal = ALL } = entry;\n if (judgement.kind === \"delete\") return [removal];\n if (judgement.writes.length === 0) return [update];\n return [\n ...new Set([\n ...judgement.writes.map((field) => entry.writes?.get(field) ?? update),\n ...(judgement.marks ? [removal] : []),\n ]),\n ];\n}\n/**\n * A domain some of whose layers hold entries: a model some layer holds an\n * entry on is judged, so a link to it is not written unjudged.\n */\nclass EntryDomain extends FilterDomain {\n override restrictsLinkWrite(queries: Queries, model: AnyModel): boolean {\n // A model's entries are bound only where some layer declares one.\n return (\n super.restrictsLinkWrite(queries, model) ||\n this.rows.rules?.get(model[\"~\"].names.ts!) !== undefined\n );\n }\n}\n\n/**\n * A domain whose layers say which rows a write may take (`only`) or hold an\n * entry given lazily: under a `judgement`, a model's predicate takes each\n * layer's predicates of the write it judges beside its filters (R2, R3), and an entry\n * given lazily brings its `read.where` here.\n */\nclass JudgedDomain extends EntryDomain {\n protected override key(\n name: string,\n excluded: readonly number[],\n judgement?: WriteJudgement\n ): string {\n const judged = this.rows.rules?.get(name) && judgement;\n return judged\n ? `${name} ${excluded} ${judged.kind}${judged.marks ? \"+\" : \"\"} ${[...judged.writes].sort()}`\n : super.key(name, excluded);\n }\n protected override layers(\n name: string,\n inputs: readonly Input[] | undefined,\n excluded: readonly number[],\n judgement?: WriteJudgement\n ): (readonly [number, readonly Input[]])[] {\n const entries = this.rows.rules?.get(name);\n if (entries === undefined) return super.layers(name, inputs, excluded);\n const layers: (readonly [number, Input[]])[] = [];\n const count = Math.max(inputs?.length ?? 0, entries.length);\n for (let layer = 0; layer < count; layer++) {\n if (excluded.includes(layer)) continue;\n const own = entries[layer];\n layers.push([\n layer,\n [\n own?.read,\n inputs?.[layer],\n ...(own && judgement ? judgedInputs(own, judgement) : []),\n ].filter(given),\n ]);\n }\n return layers;\n }\n}\n\n/** What prepares the call facts of a chain whose layers hold entries. */\nconst prepareEntries = /* @__PURE__ */ preparer(EntryDomain);\n/** What prepares them where a layer takes rows by `only`: brought by `only` and `lazy`. */\nexport const prepareJudged = /* @__PURE__ */ preparer(JudgedDomain);\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\n/** The keys of a draft that hold one predicate, each admitted as one. */\nconst SINGLE = [\"read\", \"shown\", \"update\", \"delete\", \"place\", \"check\"] as const;\n/** The keys of a draft that hold one predicate per field, each written at its own name but `facts`. */\nconst PER_FIELD = [\"writes\", \"moves\", \"reads\", \"facts\"] as const;\n\n/**\n * The self relations `acyclic` names, each checked to be one of `model`'s\n * to itself holding its key: only those can loop, so only an update that\n * writes one of those keys asks them. Given as a function, they are read\n * and checked then; as a list, now.\n */\nfunction cyclesOf(\n { schema, refuse }: Admission,\n name: string,\n declared: unknown\n): LazyRelations {\n const model = schema[name]!;\n const { relations } = model[\"~\"].state;\n const keyed = Object.keys(relations).filter((relation) => {\n const held = relations[relation]![\"~\"];\n return held.state.foreignKey !== undefined && held.settleTarget() === model;\n });\n const checked = (listed: unknown): readonly string[] => {\n if (!Array.isArray(listed))\n return refuse(\n name,\n `${name}.acyclic`,\n \"lists relations, or is a function returning them\"\n );\n for (const relation of listed)\n if (!keyed.includes(relation))\n refuse(\n name,\n `${name}.acyclic.${relation}`,\n \"names no to-one relation of the model to itself holding its key\"\n );\n return listed;\n };\n let resolved: readonly string[] | undefined;\n const resolve = () =>\n (resolved ??= checked(\n typeof declared === \"function\" ? declared() : declared\n ));\n if (typeof declared !== \"function\") resolve();\n return { candidates: keyed, resolve };\n}\n\n/** One model's draft with every predicate admitted: the layer's entry. */\nexport function admitDraft(\n admission: Admission,\n name: string,\n draft: EntryDraft,\n references: References,\n of?: string\n): Mutable<AdmittedEntry> {\n const admit = (place: string, where: unknown) =>\n admission.admit(name, `${name}.${place}`, where, references, of);\n const out: Mutable<AdmittedEntry> = { judge: draft.judge, as: draft.as };\n if (draft.acyclic !== undefined)\n out.cycles = cyclesOf(admission, name, draft.acyclic);\n for (const key of SINGLE)\n if (draft[key] !== undefined) out[key] = admit(key, draft[key]);\n for (const key of PER_FIELD) {\n const given = draft[key];\n const place = key === \"facts\" ? \"read.select\" : key;\n if (given !== undefined)\n out[key] = new Map(\n [...given].map(([field, where]) => [\n field,\n admit(`${place}.${field}`, where),\n ])\n );\n }\n return out;\n}\n\n/**\n * Every layer's entries bound to `chain`, each model's taken the first time\n * it is read, an entry given lazily read then. A model no\n * layer gives as a function is taken now: its refusals are the\n * application's, as they would be at admission.\n */\nfunction bindEntries(chain: ResolvedExtensionChain): BoundEntries {\n const layers = chain.rules!;\n // What the chain's layers brought: one value per kind, whichever brought it.\n const brought: NonNullable<RuleLayer[\"brings\"]> = {};\n for (const layer of layers) Object.assign(brought, layer.brings);\n const { judge, project, prepare = prepareEntries, keys, lazy } = brought;\n const declares = (model: string) =>\n layers.some((layer) => Object.hasOwn(layer.rules, model));\n const built = new Map<string, readonly (AdmittedEntry | undefined)[]>();\n const get = (\n model: string\n ): readonly (AdmittedEntry | undefined)[] | undefined =>\n declares(model)\n ? memo(built, model, () => {\n const out = layers.map(({ rules, extension }) => {\n const entry = rules[model];\n // Only `lazy` writes an entry as a function: it reads itself.\n return typeof entry === \"function\"\n ? entry(chain, extension)\n : entry;\n });\n keys?.(model, out);\n return out;\n })\n : undefined;\n for (const layer of layers)\n for (const model of Object.keys(layer.rules))\n if (layers.every((other) => typeof other.rules[model] !== \"function\"))\n get(model);\n return {\n rules: { has: declares, get },\n judge,\n project,\n // An entry given lazily is read later: its calls carry their values.\n ...(lazy && {\n lazy,\n filters: (model: string, layer: number) => get(model)?.[layer]?.filters,\n }),\n prepare,\n };\n}\n\n/** What the words that write entries bring: their admission and their binding. */\nexport const ENTRIES: EntryHost = {\n admit: (admitting, layer, filtersOf, references) =>\n Object.fromEntries(\n Object.entries(layer.rules).map(([name, draft]) => [\n name,\n typeof draft === \"function\"\n ? draft(admitting, filtersOf)\n : admitDraft(admitting, name, draft, references),\n ])\n ),\n bind: bindEntries,\n};\n\n/**\n * The entry of the model a word is written on, made at the first word that\n * writes one, with what admits and binds them.\n */\nexport function entryOf(site: Site): EntryDraft {\n // Asked first: where nothing takes an entry (a default's field), it refuses.\n const entry = site.entry();\n site.layer!.host ??= ENTRIES;\n return entry;\n}\n","/** MySQL's spelling of a judged write (`../../judged.ts`). */\nimport { sql } from \"@sql\";\nimport { afterHead, type JudgedSpelling } from \"../../judged\";\n\nexport const MYSQL_JUDGED: JudgedSpelling = {\n // The refusal is an invalid path (3143), never the invalid text (3141)\n // a premise fails with.\n refused: \"JSON_EXTRACT('{}', '__viborm_refused__')\",\n /**\n * One `UNION ALL SELECT` arm per row after the typed head, each typed\n * against the arms before it: 65,535 arms measured, so the bind budget is\n * reached first.\n */\n typedRows: (a, typed, rows, alias) =>\n afterHead(\n a,\n typed,\n sql.join(\n rows.map((row) => sql`SELECT ${sql.join(row, \", \")}`),\n \" UNION ALL \"\n ),\n alias\n ),\n};\n","/** PostgreSQL's spelling of a judged write (`../../judged.ts`). */\nimport { sql } from \"@sql\";\nimport type { JudgedSpelling } from \"../../judged\";\nimport { rowValues } from \"../../shared/standard-sql\";\n\nexport const POSTGRES_JUDGED: JudgedSpelling = {\n // The refusal names its sentinel (22P02, `invalid input syntax for type\n // integer: \"__viborm_refused__\"`), which no caller's division by zero\n // does; the text is a sublink, which PostgreSQL does not fold while\n // planning, so it is evaluated only where it is reached.\n refused: \"CAST((SELECT '__viborm_refused__') AS integer)\",\n /**\n * The produced rows as a `VALUES` list: PostgreSQL parses each `UNION ALL`\n * arm one recursion deeper (`54001`, stack depth, at 8,000 rows on 16.14),\n * and a list is no deeper for its length. A `VALUES` column is typed by its\n * own rows, an unknown parameter as `text`, so the first row takes each\n * column's type from a NULL of the table's row type (`COALESCE`, the rule\n * a `UNION` arm met), beside the list, as a one-row FROM item. The NULL is\n * cast to the table's type, never read as `SELECT \"qN\" FROM table AS \"qN\"`:\n * there a column named `qN` would win over the whole-row reference (42809),\n * and the cast reads no relation at all.\n */\n typedRows: (a, typed, rows, alias) => {\n // Every adapter's `escape` is an arrow: it reads no `this`.\n const { escape: quoted } = a.identifiers;\n const name = quoted(typed.alias);\n const [first, ...rest] = rows;\n const typedFirst = first!.map(\n (value, index) =>\n sql`COALESCE(${value}, (${name}.\"row\").${quoted(typed.columns[index]!)})`\n );\n return sql`(SELECT NULL::${typed.table} AS \"row\") AS ${name} CROSS JOIN LATERAL (VALUES ${sql.join(\n [typedFirst, ...rest].map(rowValues),\n \", \"\n )}) AS ${quoted(alias)}(${sql.join(typed.columns.map(quoted), \", \")})`;\n },\n};\n","/** SQLite's spelling of a judged write (`../../judged.ts`). */\nimport { sql } from \"@sql\";\nimport { afterHead, type JudgedSpelling } from \"../../judged\";\nimport { rowValues } from \"../../shared/standard-sql\";\n\nexport const SQLITE_JUDGED: JudgedSpelling = {\n // The refusal names its sentinel (`bad JSON path: '__viborm_refused__'`).\n refused: \"json_extract('{}', '__viborm_refused__')\",\n /**\n * A multi-row `VALUES` is the one compound SQLite does not count against\n * `SQLITE_MAX_COMPOUND_SELECT` (500 terms; measured on 3.53.2: 500 `UNION\n * ALL SELECT` arms refused, 10,922 `VALUES` rows read), so the produced\n * rows follow their typed head as one: the head's columns still type every\n * row, as an arm's did (affinity and collation measured equal).\n */\n typedRows: (a, typed, rows, alias) =>\n afterHead(\n a,\n typed,\n sql`VALUES ${sql.join(rows.map(rowValues), \", \")}`,\n alias\n ),\n};\n","/**\n * How each SQL dialect spells the judgement of the rows a write produces\n * (permissions plan K4, R4): the assertion a produced row is held to, and\n * the produced rows as one FROM item typed by their table. Only what judges\n * written rows imports this module, by the dialect of the call's driver, so\n * an application that judges none does not carry these spellings; the\n * call's adapter quotes the identifiers.\n */\nimport type { Dialect, SqlDialect } from \"@drivers/types\";\nimport { type Sql, sql } from \"@sql\";\nimport type { DatabaseAdapter } from \"./database-adapter\";\nimport { MYSQL_JUDGED } from \"./databases/mysql/judged\";\nimport { POSTGRES_JUDGED } from \"./databases/postgres/judged\";\nimport { SQLITE_JUDGED } from \"./databases/sqlite/judged\";\n\n/** The produced rows' table, read empty: what types their columns. */\nexport interface TypedHead {\n /** The empty read of those columns (`… WHERE FALSE`). */\n readonly head: Sql;\n readonly from: Sql;\n /** The table itself, unaliased: its row type names the columns' types. */\n readonly table: Sql;\n readonly alias: string;\n readonly columns: readonly string[];\n}\n\n/** One dialect's spelling of a judged write. */\nexport interface JudgedSpelling {\n /**\n * What fails the statement where a produced row is refused: an error\n * naming the sentinel `__viborm_refused__`, which no caller's own failure\n * in the same statement does (E5.6), so the driver maps it by the\n * sentinel and the marker of {@link holds}.\n */\n readonly refused: string;\n /**\n * `rows` as ONE FROM item `alias` whose columns are `typed.columns`, each\n * typed as that column of the table `typed.from` reads under\n * `typed.alias`; a row lists its values in `columns`' order and may refer\n * to the enclosing query. The form is the dialect's, because every one\n * spends a different limit on the row count first; the bind budget stays\n * the only bound on a chunk (ENG-3, review 2).\n */\n readonly typedRows: (\n a: DatabaseAdapter,\n typed: TypedHead,\n rows: readonly (readonly Sql[])[],\n alias: string\n ) => Sql;\n}\n\n/**\n * The produced rows after their typed head, as one derived table: the head's\n * columns type every row (the forms of SQLite and MySQL).\n */\nexport const afterHead = (\n a: DatabaseAdapter,\n typed: TypedHead,\n rows: Sql,\n alias: string\n): Sql =>\n sql`(${typed.head} UNION ALL ${rows}) AS ${a.identifiers.escape(alias)}`;\n\n/**\n * Each SQL dialect's spelling, by the name its drivers declare. The adapter\n * interface no longer makes a new SQL dialect spell a judged write, so this\n * table does: one left out is a compile error, not a judged write failing\n * on `undefined` at its first call.\n */\nexport const JUDGED: Partial<Record<Dialect, JudgedSpelling>> = {\n postgresql: POSTGRES_JUDGED,\n sqlite: SQLITE_JUDGED,\n mysql: MYSQL_JUDGED,\n} satisfies Record<SqlDialect, JudgedSpelling>;\n\n/**\n * A one-column SELECT answering 1 where `condition` holds (over `from`'s\n * row when given), failing the statement it is part of otherwise, NULL\n * included: the guard a write carries for the row it produces, read as a\n * scalar inside that write, and marked as a judgement by its column's name.\n */\nexport const holds = (\n a: DatabaseAdapter,\n spelling: JudgedSpelling,\n condition: Sql,\n from?: Sql\n): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE ${sql.raw(spelling.refused)} END AS ${a.identifiers.escape(\"__viborm_judged__\")}${from ? sql` FROM ${from}` : sql``}`;\n","/**\n * What a row predicate reads of the row it judges: asked where a write is\n * judged again only if it changes what its judgement reads.\n */\nimport type { PreparedPredicate } from \"@query-engine/raptor3/shared/query\";\nimport { hopFieldsOf } from \"@query-engine/raptor3/shared/storage\";\n\n/**\n * Whether `predicate`, judged over a row of `model`, may read one of\n * `fields` of that row: an operation's column or field operand, a\n * relation's own side of its link (a junction's: the row's keys), and in a\n * relation body `depth` bodies below the row, an operand that compares one\n * of them (`row(field, depth)`); an `exists` body is a root of its own and\n * reads only those. Anything it cannot answer for (an aggregate, a window)\n * reads them all. A row that differs from another only outside what a\n * predicate reads gets the same answer from it, against the same rows.\n */\nexport function readsAny(\n predicate: PreparedPredicate,\n fields: ReadonlySet<string>,\n keys: readonly string[],\n depth = 0\n): boolean {\n switch (predicate.kind) {\n case \"and\":\n case \"or\":\n return predicate.predicates.some((member) =>\n readsAny(member, fields, keys, depth)\n );\n case \"not\":\n case \"layer\":\n return readsAny(predicate.predicate, fields, keys, depth);\n case \"always\":\n case \"condition\":\n return false;\n case \"relation\":\n case \"exists\":\n return (\n (predicate.kind === \"relation\" &&\n depth === 0 &&\n (predicate.edge.kind === \"reference\"\n ? hopFieldsOf(predicate.edge)\n : keys\n ).some((field) => fields.has(field))) ||\n (predicate.predicate !== undefined &&\n readsAny(predicate.predicate, fields, keys, depth + 1))\n );\n case \"operation\": {\n const operands = [predicate.operand, ...(predicate.operands ?? [])];\n const field = (operand: (typeof operands)[number]) =>\n operand?.kind === \"field\" &&\n (depth === 0 || operand.up === depth) &&\n fields.has(operand.scalar.field);\n if (depth > 0) return operands.some(field);\n return (\n predicate.target.kind !== \"column\" ||\n fields.has(predicate.target.scalar.field) ||\n operands.some(\n (operand) =>\n field(operand) ||\n (operand?.kind === \"sql\" &&\n operand.operands.some(\n (member) =>\n member.kind === \"field\" && fields.has(member.scalar.field)\n ))\n )\n );\n }\n default:\n return true;\n }\n}\n","/**\n * The row a write would leave, judged in the statement that writes it: the\n * SQL an extension's `place` and `moves` rules add to an INSERT or an UPDATE.\n * The engine lowers predicates and names rows; what is judged, and how the\n * judgement rides the write, is stated here, beside what declares it.\n */\nimport { assembleAdapterSelect } from \"@adapters/adapter-internals\";\nimport { type JudgedSpelling, holds as judgedHolds } from \"@adapters/judged\";\nimport {\n NO_RELATIONS,\n type PreparedPredicate,\n type PreparedSelector,\n rowValue,\n throughDerived,\n wholeValue,\n} from \"@query-engine/raptor3/shared/query\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { SqlQueries } from \"@query-engine/raptor3/shared/sql-queries\";\nimport type { AnyModel } from \"@schema/model\";\nimport { Sql, sql } from \"@sql\";\nimport { fold } from \"./layers\";\nimport { readsAny } from \"./reads\";\n\n/**\n * The rows of `model` a write produces, as ONE FROM item read under\n * `alias`: every stored field, each row's value as `row` lowers it (NULL\n * where it says nothing). The model's own columns type them, through an\n * empty read of the table, so a bound value takes its column's type where\n * PostgreSQL would resolve a bare parameter as text; how the rows follow\n * it is the dialect's (`typedRows`), so a chunk is bounded by its binds\n * alone.\n */\nfunction producedRows(\n q: SqlQueries,\n spelling: JudgedSpelling,\n model: AnyModel,\n rows: readonly ((field: string) => Sql | undefined)[],\n alias: string\n): Sql {\n const a = q.adapter;\n const fields = q.schema.storedFields(model);\n const typed = q.alias();\n const from = q.table(model, typed);\n const head = assembleAdapterSelect(a, {\n columns: sql.join(\n fields.map((field) => q.column(model, field, typed)),\n \", \"\n ),\n from,\n where: a.literals.false(),\n });\n return spelling.typedRows(\n a,\n {\n head,\n from,\n table: q.table(model),\n alias: typed,\n columns: fields.map((field) => q.columnName(model, field)),\n },\n rows.map((row) => fields.map((field) => row(field) ?? a.literals.null())),\n alias\n );\n}\n/**\n * The row read as `alias` does not reach itself through `relation`, a\n * to-one relation of its model to itself: no row its new target leads to,\n * that target included, is the row. The walk is physical, read under no\n * domain: a cycle through a row the caller cannot see is still a cycle.\n */\nfunction outsideOwnSubtree(\n q: SqlQueries,\n model: AnyModel,\n relation: string,\n alias: string\n): Sql {\n const a = q.adapter;\n const { cte, cteName, walk, childColumns } = q.walk(\n q.schema.membership(model, relation),\n alias,\n { depth: false, self: false },\n false\n );\n return a.filters.none(\n sql`${cte} ${assembleAdapterSelect(a, {\n columns: sql.raw(\"1\"),\n from: a.identifiers.aliased(a.identifiers.escape(cteName), walk),\n where: q.sameRow(\n model,\n alias,\n childColumns.map((name) => a.identifiers.column(walk, name))\n ),\n })}`\n );\n}\n/**\n * `predicate` over a produced row whose fields' nullness the write states\n * (`nulls`: field to whether its value is null), each null test of such a\n * field replaced by its outcome: the values a write sets fold into its\n * judgement, so an arm on a key it leaves null does not reach the statement.\n * Only the row's own columns: a relation reads other rows, and is kept as it\n * is.\n */\nconst foldKnownNulls = (\n predicate: PreparedPredicate,\n nulls: ReadonlyMap<string, boolean>\n): PreparedPredicate =>\n fold(\n predicate,\n // The conditions of a call were folded before it is judged: every leaf\n // here is an operation, which the first test only narrows.\n (leaf) =>\n leaf.kind === \"operation\" &&\n leaf.operator === \"equals\" &&\n leaf.target.kind === \"column\" &&\n leaf.target.path === undefined &&\n leaf.operand?.kind === \"value\" &&\n leaf.operand.value === null &&\n leaf.target.scalar.physical.scalar[\"~\"].state.type !== \"json\"\n ? nulls.get(leaf.target.scalar.field)\n : undefined,\n false\n );\n/**\n * The SELECT `select` makes of the guard `judged` puts on the produced row\n * `from` reads (and, for each `acyclic` relation, the row outside its own\n * subtree), read with the statement's shared bodies: the adapter's\n * assertion, 1 or the statement that carries it fails before it writes.\n * `undefined` where nothing is left to judge: the call drops every layer\n * `judged` is made of (R6).\n */\nfunction holds(\n q: SqlQueries,\n spelling: JudgedSpelling,\n model: AnyModel,\n judged: Pick<PreparedSelector, \"model\" | \"predicate\"> | undefined,\n alias: string,\n nulls: ReadonlyMap<string, boolean>,\n select: (guard: Sql) => Parameters<typeof assembleAdapterSelect>[1],\n from?: Sql,\n acyclic: readonly string[] = NO_RELATIONS\n): Sql | undefined {\n const a = q.adapter;\n return q.sharing(() => {\n const outer = q.known;\n q.known = { alias, nulls, fold: foldKnownNulls };\n let lowered: Sql | undefined;\n try {\n lowered = judged && q.lowerSelector(judged, alias);\n } finally {\n q.known = outer;\n }\n const conditions = [\n ...(lowered === undefined ? [] : [lowered]),\n ...acyclic.map((relation) =>\n outsideOwnSubtree(q, model, relation, alias)\n ),\n ];\n return conditions.length === 0\n ? undefined\n : assembleAdapterSelect(\n a,\n select(\n a.subqueries.scalar(\n judgedHolds(a, spelling, a.operators.and(...conditions), from)\n )\n )\n );\n });\n}\n/**\n * The SELECT an INSERT of `rows` reads its values from when the rows it\n * creates are judged (R4): each row a value of the derived table, kept\n * where `judged` holds of it and failing the statement where it does not,\n * before any row is written or any constraint is checked. One statement:\n * nothing it writes is visible to its own judgement.\n */\nexport function producedSource(\n q: SqlQueries,\n spelling: JudgedSpelling,\n model: AnyModel,\n columns: readonly string[],\n rows: readonly Input[],\n judged: PreparedSelector\n): Sql | undefined {\n const alias = q.alias();\n const written = new Set(columns);\n const from = producedRows(\n q,\n spelling,\n model,\n rows.map(\n (row) => (field) =>\n written.has(field) ? q.fieldValue(model, field, row[field]) : undefined\n ),\n alias\n );\n // A field's nullness folds where every row states the same one; a field\n // no row writes is null in each.\n const nulls = new Map<string, boolean>();\n for (const field of q.schema.storedFields(model)) {\n const states = new Set(\n rows.map((row) => {\n const value = written.has(field) ? row[field] : null;\n return value instanceof Sql\n ? undefined\n : value === null || value === undefined;\n })\n );\n const [state] = states;\n if (states.size === 1 && state !== undefined) nulls.set(field, state);\n }\n return holds(q, spelling, model, judged, alias, nulls, (guard) => ({\n columns: sql.join(\n columns.map((field) => q.column(model, field, alias)),\n \", \"\n ),\n from,\n where: sql`${guard} = 1`,\n }));\n}\n/**\n * The WHERE of an UPDATE of `model` assigning `values` that judges the\n * rows it produces (R4): the keys of the rows `candidates` selects\n * (lowered at the alias it is handed; the first `limit` in key order),\n * read ONCE, before the statement writes any of them, each group of one\n * key kept where its produced row's assertion holds (the row as it stands\n * with the assignments applied, typed as {@link producedRows}): 1, or the\n * statement fails before it writes.\n *\n * An aggregate is computed over the rows its WHERE kept, so a row the\n * update does not write is never judged: a guard in a select list or a\n * WHERE is not, since PostgreSQL and MySQL flatten an `IN` subquery and\n * order its conditions by cost (measured: a viewed row's refused guard\n * raised before the predicate that excludes it). A set read once is\n * judged against the rows as they stand before the write, never against\n * a row the statement wrote earlier: SQLite and MySQL evaluate an\n * UPDATE's own SET row by row (measured: a team's lead demoted early made\n * its other members' new rows unwritable). On MySQL, which refuses to read\n * the written table from its own subquery, the set is a derived table,\n * materialized before the write (`#capped`'s form). `undefined` where\n * nothing is left to judge.\n */\nexport function producedWhere(\n q: SqlQueries,\n spelling: JudgedSpelling,\n model: AnyModel,\n candidates: (alias: string) => Sql | undefined,\n values: Input,\n judged: PreparedSelector | undefined,\n acyclic: readonly string[] = NO_RELATIONS,\n limit?: number\n): Sql | undefined {\n if (judged === undefined && acyclic.length === 0) return undefined;\n const a = q.adapter;\n const row = q.alias();\n const produced = q.alias();\n const current = (field: string) => q.column(model, field, row);\n const rowKeys = q.schema.keys(model);\n // A value only the database computes (a list append, an exact\n // decimal's multiply or divide) has no value to judge: it is refused\n // where the judgement reads it (`updateValue`), and stands as it was\n // where nothing does, since no answer depends on it.\n const unread = (field: string) =>\n !(\n q.namesUpdate(model, field, values[field]) ||\n (judged?.predicate &&\n readsAny(judged.predicate, new Set([field]), rowKeys)) ||\n acyclic.some((relation) => {\n const edge = q.schema.membership(model, relation);\n return (\n edge.kind === \"reference\" &&\n edge.pairs.some((pair) => pair.source === field)\n );\n })\n );\n const from = producedRows(\n q,\n spelling,\n model,\n [\n (field) =>\n values[field] === undefined || unread(field)\n ? current(field)\n : q.updateValue(model, field, values[field], current(field)),\n ],\n produced\n );\n // A write's values hold no `undefined`: `schema.scalars` leaves it out.\n const nulls = new Map<string, boolean>();\n for (const [field, value] of Object.entries(values)) {\n const whole = wholeValue(value);\n if (whole && !(whole.value instanceof Sql))\n nulls.set(field, whole.value === null);\n }\n const keys = q.keyOrder(model).map(current);\n const set = holds(\n q,\n spelling,\n model,\n judged,\n produced,\n nulls,\n (guard) => ({\n columns: sql.join(keys, \", \"),\n from: q.table(model, row),\n where: candidates(row),\n groupBy: sql.join(keys, \", \"),\n having: sql`${a.aggregates.min(guard)} = 1`,\n ...(limit !== undefined && {\n orderBy: q.ascendingKeys(model, row),\n limit: q.value(limit),\n }),\n }),\n from,\n acyclic\n );\n if (set === undefined) return undefined;\n const table = model[\"~\"].names.sql!;\n return a.operators.in(\n rowValue(q.keyOrder(model).map((field) => q.column(model, field, table))),\n a.subqueries.scalar(\n a.capabilities.supportsMutationTargetInSubquery\n ? set\n : throughDerived(a, set, q.alias())\n )\n );\n}\n","/**\n * What judges the rows a write produces, for one prepared domain: the entries'\n * `place`, `moves` and `acyclic` rules, the refusal a judged write fails\n * with, and what an upsert says of a row it located. Brought by `check`:\n * a program whose rules judge no produced row does not hold it.\n */\nimport { JUDGED } from \"@adapters/judged\";\nimport { ForbiddenError } from \"@errors\";\nimport {\n NO_RELATIONS,\n type PreparedSelector,\n} from \"@query-engine/raptor3/shared/query\";\nimport type { WriteJudgement } from \"@query-engine/raptor3/shared/row-scope\";\nimport { type Input, memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { SqlOperationContext } from \"@query-engine/raptor3/shared/sql-operation-context\";\nimport type { SqlQueries } from \"@query-engine/raptor3/shared/sql-queries\";\nimport { nameOf, unsupported } from \"@query-engine/raptor3/shared/terms\";\nimport type { Question } from \"@query-engine/raptor3/write/statements\";\nimport type { PreparedGuardFailure } from \"@query-engine/types\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport { ALL, given, judgedInputs } from \"./entries\";\nimport { producedSource, producedWhere } from \"./produced\";\nimport { readsAny } from \"./reads\";\nimport type { PreparedDomain } from \"./row-domain\";\n\n/** What the engine and the drivers ask of what judges a domain's writes. */\nexport type Judge = ReturnType<typeof judgeOf>;\n\n/** What judges the rows a write produces, for one domain: brought by `check`. */\nexport const judgeOf = (domain: PreparedDomain) => {\n const cache = new Map<string, PreparedSelector | null>();\n const layersOf = (model: AnyModel) =>\n domain.rows.rules?.get(model[\"~\"].names.ts!);\n const judge = {\n /**\n * The values the judgement of a created row of `model` binds, beside the\n * rows a statement inserts: what a chunk of them leaves of the driver's\n * bind budget.\n */\n binds(q: SqlQueries, model: AnyModel): number {\n const placed = judge.produced(model);\n return (placed && q.lowerSelector(placed)?.values.length) ?? 0;\n },\n /**\n * The SELECT an INSERT of `rows` of `model` reads its values from, where\n * the rows it creates are judged, and what the statement says when one is\n * refused, in the name of `relation` where they are created through one.\n */\n inserted(\n q: SqlQueries,\n operation: SqlOperationContext,\n model: AnyModel,\n fields: readonly string[],\n rows: readonly Input[],\n relation?: string\n ):\n | { readonly probe: Sql; readonly stops: PreparedGuardFailure }\n | undefined {\n const placed = judge.produced(model);\n if (placed === undefined) return undefined;\n // A row of defaults only has no value to judge before it is written.\n if (fields.length === 0)\n unsupported(\n `Cannot create a '${nameOf(model)}' row that writes no field: its placement is judged on the values it writes.`\n );\n const probe = producedSource(\n q,\n JUDGED[operation.driver.dialect]!,\n model,\n fields,\n rows,\n placed\n );\n return (\n probe && {\n probe,\n stops: judge.refusal(\n operation.operation,\n model,\n undefined,\n \"create\",\n relation\n ),\n }\n );\n },\n /**\n * The WHERE of an update of the rows `question` names (`candidates`, at\n * the alias it is handed) assigning `values`, where the rows it leaves\n * are judged at `judgement`, and what the statement says when one is\n * refused.\n */\n updated(\n q: SqlQueries,\n operation: SqlOperationContext,\n question: Question,\n candidates: (alias: string) => Sql | undefined,\n values: Input,\n judgement: WriteJudgement,\n limit?: number\n ):\n | { readonly where: Sql; readonly stops: PreparedGuardFailure }\n | undefined {\n const { model } = question;\n const where = producedWhere(\n q,\n JUDGED[operation.driver.dialect]!,\n model,\n candidates,\n values,\n judge.produced(model, judgement, Object.keys(values)),\n judge.cycles(model, judgement),\n limit\n );\n return (\n where && {\n where,\n stops: judge.refusal(\n operation.operation,\n model,\n judgement,\n question.verb,\n (question.member?.edge ?? question.through)?.name\n ),\n }\n );\n },\n /**\n * What a write of `operation` says when the row it would leave is\n * refused: the `verb` it is written with through `relation`, where it is\n * nested; else why, where it writes a field some layer `moves` judges\n * again (a relation's write names its key fields).\n */\n refusal(\n operation: string,\n model: AnyModel,\n judgement?: WriteJudgement,\n verb?: string,\n relation?: string\n ): PreparedGuardFailure {\n if (verb && relation)\n return {\n kind: \"nestedWrite\",\n relation,\n message: `Cannot ${verb} relation '${relation}': the record it writes is not permitted.`,\n raceable: false,\n };\n const layers = layersOf(model);\n const moved =\n judgement?.writes.filter((field) =>\n layers?.some((layer) => layer?.moves?.has(field))\n ) ?? [];\n return {\n kind: \"forbidden\",\n message: `${operation} produced a row that is not permitted.`,\n raceable: false,\n ...(moved.length > 0 && { reason: `it writes ${moved.join(\", \")}` }),\n };\n },\n /**\n * What an upsert says when it located no row and its create is refused\n * for the key it named: where no row of the model may be updated at all,\n * the row it located exists, and the update is what is not permitted.\n */\n located(model: AnyModel): ((cause: Error) => Error) | undefined {\n const never = layersOf(model)?.some((layer) => {\n const update = layer?.update;\n const members = update?.OR;\n return (\n Array.isArray(members) &&\n members.length === 0 &&\n Object.keys(update!).length === 1\n );\n });\n return never\n ? (cause) =>\n new ForbiddenError(model[\"~\"].names.ts!, \"update\", {\n reason: \"the row this upsert locates exists\",\n cause,\n })\n : undefined;\n },\n /**\n * What the row a write of `model` produces is judged at, as a value,\n * against the rows as they stand before the write (R4): a created row\n * (no `judgement`) at each layer's `place`; an updated one at the\n * predicates that judged its old row, `read` and its `update.where`'s (WITH\n * CHECK), and its written fields' `moves`. A write that states its\n * candidates' judgement in its own statement names the fields it\n * `assigned`: where it assigns none of what judged its old row, that\n * judgement is the old row's and is not stated twice. `undefined` where\n * no layer judges it: no entry, no `place` for a create, a delete, an\n * update nothing judges.\n */\n produced(\n model: AnyModel,\n judgement?: WriteJudgement,\n assigned?: readonly string[]\n ): PreparedSelector | undefined {\n const entries = layersOf(model);\n if (judgement?.kind === \"delete\" || entries === undefined)\n return undefined;\n const changed = assigned && new Set(assigned);\n const keys = domain.queries.schema.keys(model);\n return (\n memo(\n cache,\n judgement\n ? `update ${model[\"~\"].names.ts} ${[...judgement.writes].sort()} ${assigned ? [...assigned].sort() : \"*\"}`\n : `create ${model[\"~\"].names.ts}`,\n () => {\n const layers: (readonly [number, Input[]])[] = [];\n for (const [layer, own] of entries.entries()) {\n // A layer judges the rows its writes produce where a check said so.\n if (own?.judge === undefined) continue;\n // What judged the old row judges the new one, unless the write\n // assigns nothing it reads: then the new row's answer is the old\n // row's, which the statement's own candidates already state.\n const checked = judgement\n ? [\n own.read ?? ALL,\n ...judgedInputs(own, judgement),\n own.check,\n ].filter(given)\n : [];\n const unchanged =\n changed !== undefined &&\n checked.every((where) => {\n const { predicate } = domain.prepare(model, where);\n return (\n predicate === undefined ||\n !readsAny(predicate, changed, keys)\n );\n });\n const wheres = judgement\n ? [\n ...(unchanged ? [] : checked),\n ...judgement.writes.map((field) => own.moves?.get(field)),\n ]\n : [own.place];\n layers.push([layer, [...new Set(wheres.filter(given))]]);\n }\n return domain.conjunction(model, layers);\n }\n ) ?? undefined\n );\n },\n /**\n * The self relations whose links an update judged at `judgement` must\n * keep acyclic (R4): each layer's `acyclic` relations of `model` whose\n * key fields it writes.\n */\n cycles(model: AnyModel, judgement: WriteJudgement): readonly string[] {\n const entries = layersOf(model);\n if (judgement.kind === \"delete\" || entries === undefined)\n return NO_RELATIONS;\n const relations = new Set<string>();\n const written = (relation: string) => {\n const edge = domain.queries.schema.membership(model, relation);\n return (\n judgement.writes.includes(relation) ||\n (edge.kind === \"reference\" &&\n edge.pairs.some((pair) => judgement.writes.includes(pair.source)))\n );\n };\n for (const own of entries) {\n const acyclic = own?.cycles;\n // Named only where the update writes one of the keys that could be.\n if (acyclic?.candidates.some(written))\n for (const relation of acyclic.resolve())\n if (written(relation)) relations.add(relation);\n }\n return relations.size === 0 ? NO_RELATIONS : [...relations];\n },\n };\n return judge;\n};\n","/**\n * Each predicate of a rule admitted once, when its extension is applied,\n * through its model's `where` schema: a misspelt key fails here, never at\n * the first read, and the engine prepares what a caller's `where` would be\n * (K1(a)). The words are read as they are: `arg` and `now` are call values\n * (parameters), `row` an enclosing column, `when`, `unless` and `provided`\n * conditions folded per call, `exists` another model's rows.\n */\n\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError } from \"@errors\";\nimport type {\n CallRows,\n JudgedEntry,\n RowDomain,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { ModelState } from \"@schema/model\";\nimport { createSchemaRegistry } from \"@validation/builder\";\nimport { validateSchema } from \"@validation/primitives/helpers\";\nimport {\n type AdmittedFilters,\n admittingDomainPredicate,\n type FilterWord,\n} from \"@validation/primitives/parameter\";\nimport type { SchemaRegistryLookup } from \"@validation/types\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { ResolvedExtensionChain } from \"./chain-state\";\nimport type { Projection } from \"./projection\";\nimport type { PreparedDomain } from \"./row-domain\";\nimport { type Admitting, PredicateWord } from \"./rule-words\";\n\n/**\n * What predicates read of their call, as admission makes their parameters:\n * each argument they name, and `undefined` for the call's instant.\n */\nexport type References = Set<string | undefined>;\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\n/**\n * One model's entry of one rule layer beyond its filters, as its words\n * wrote it (`JudgedEntry` with its predicates raw): admitted, it is the\n * layer's `JudgedEntry`. An entry given lazily holds its filters here too,\n * since what filters is bound before any entry is resolved.\n */\nexport type EntryDraft = Mutable<Omit<JudgedEntry<unknown>, \"cycles\">> & {\n writes?: Map<string, unknown>;\n moves?: Map<string, unknown>;\n reads?: Map<string, unknown>;\n facts?: Map<string, unknown>;\n /** As written: a list or a function returning one, checked where it is admitted. */\n acyclic?: unknown;\n root?: readonly unknown[];\n related?: readonly unknown[];\n};\n\n/**\n * One model's admitted entry, with an entry given lazily's filters and the\n * arguments its predicates name, checked against the chain it is bound to.\n */\nexport interface AdmittedEntry extends JudgedEntry {\n readonly filters?: Filters;\n readonly references?: readonly (string | undefined)[];\n}\n\n/**\n * One extension's rule parts as written, per model: its filters by purpose\n * (each a list of `where`s and words), its other keys and its\n * confinements. A function entry's keys are read when its model is first\n * read.\n */\nexport interface RuleLayer {\n readonly root: Record<string, unknown[]>;\n readonly related: Record<string, unknown[]>;\n readonly rules: Record<string, EntryDraft | LazyDraft>;\n /** Per model, what its whole-table sets hold: written by `within`. */\n confine?: Record<string, unknown>;\n /**\n * What admits and binds `rules`: set by the words that write them\n * (`entries.ts`), so a rule that only filters holds none of that code.\n */\n host?: EntryHost;\n /** What reads the call, set where an entry read later may read its call. */\n reads?: CallReads;\n /** What judges and projects, brought by the words that ask either. */\n brings?: {\n judge?: JudgedEntry[\"judge\"];\n project?: (domain: PreparedDomain) => Projection;\n /** What prepares a call's domains where a layer takes rows by `only`. */\n prepare?: CallRows[\"prepare\"];\n /** What refuses one model's projection keys across the chain's layers. */\n keys?: (\n model: string,\n layers: readonly (JudgedEntry | undefined)[]\n ) => void;\n /** Some entry is given lazily: brought by `lazy`. */\n lazy?: true;\n /** What admits and binds the confinements, brought by `within`. */\n confines?: Confines;\n };\n}\n\n/** What `within` brings: its predicates admitted, and the chain's bound. */\nexport interface Confines {\n admit(\n admission: Admission,\n written: Readonly<Record<string, unknown>>,\n references: References\n ): Record<string, Input>;\n bind(layers: readonly AdmittedLayer[]): Partial<RowDomain>;\n}\n\n/**\n * An entry given lazily (`lazy`), as its layer is admitted: what reads it\n * once, the first time its model is read, and checks the arguments it names\n * against each chain it is bound to.\n */\nexport type LazyDraft = (\n admission: Admission,\n filtersOf: FiltersOf\n) => LazyEntry;\n/** An entry given lazily as admitted: the entry as `extension` of `chain` reads it. */\nexport type LazyEntry = (\n chain: ResolvedExtensionChain,\n extension: string\n) => AdmittedEntry;\n\n/**\n * What the words that read a call bring (`call-values.ts`): each layer's\n * node read per call, and every call's values carried beside the domain.\n */\nexport interface CallReads {\n bind(\n chain: ResolvedExtensionChain,\n lazy: boolean,\n domain: RowDomain\n ): {\n readonly domain: RowDomain;\n call(facts: CallRows, values: AdmittedArgs | undefined): CallRows;\n };\n}\n\n/** One model's filters by purpose, as admitted. */\nexport interface Filters {\n readonly root?: Input;\n readonly related?: Input;\n}\n\n/** What admits one model's filters, for what admits an entry read later. */\nexport type FiltersOf = (\n name: string,\n lists: {\n readonly root?: readonly unknown[];\n readonly related?: readonly unknown[];\n },\n references: References,\n of: string\n) => Filters;\n\n/** What a layer's entries bind to, for a chain. */\nexport interface BoundEntries {\n readonly rules?: RowDomain[\"rules\"];\n readonly judge?: RowDomain[\"judge\"];\n readonly project?: RowDomain[\"project\"];\n /** An entry given lazily is read: its calls carry their values. */\n readonly lazy?: boolean;\n /** A model's filters at one layer, held by an entry given lazily. */\n readonly filters?: (model: string, layer: number) => Filters | undefined;\n /** What prepares the call facts, with what the entries judge. */\n readonly prepare: CallRows[\"prepare\"];\n}\n\n/**\n * What the words that write entries bring (`entries.ts`): what admits a layer's\n * entries once per schema, and what binds a chain's for its calls.\n */\nexport interface EntryHost {\n admit(\n admission: Admission,\n layer: RuleLayer,\n filtersOf: FiltersOf,\n references: References\n ): AdmittedLayer[\"rules\"];\n bind(chain: ResolvedExtensionChain): BoundEntries;\n}\n\n/**\n * A rule layer as admission left it: per model, its filters by purpose; its\n * other keys per model (a function entry's admitted when first read); its\n * confinements; and the arguments its predicates read.\n */\nexport interface AdmittedLayer {\n readonly extension: string;\n readonly models: { readonly [model: string]: Filters };\n readonly rules: { readonly [model: string]: AdmittedEntry | LazyEntry };\n /** What admitted `rules`, and binds them. */\n readonly host?: EntryHost;\n /** What reads the call, where some predicate of it reads one. */\n readonly reads?: CallReads;\n /** What judges and projects, brought by the words that ask either. */\n readonly brings?: RuleLayer[\"brings\"];\n readonly confine?: { readonly [model: string]: Input };\n /** What its eager predicates read of their call (`References`). */\n readonly references: readonly (string | undefined)[];\n}\n\n/** What admits the predicates of one layer, for what reads a word's keys. */\nexport interface Admission {\n readonly schema: Schema;\n /**\n * `predicate`, one of model `name`'s, at `place` in the rule, admitted\n * through the model's `where` schema; what it reads of its call is added\n * to `references` as its parameters are made. A sub-predicate parsed\n * before under the same `of` is reused and adds nothing: predicates whose\n * references are told apart take their own `of`.\n */\n readonly admit: (\n name: string,\n place: string,\n predicate: unknown,\n references: References,\n of?: string\n ) => Input;\n readonly refuse: (name: string, place: string, reason: string) => never;\n /** What reads the call, once a predicate admitted reads one. */\n reads?: CallReads;\n}\n\n/** Whether every scalar of the schema reads its value with the engine's own schema. */\nexport function nativeSchema(schema: Schema): boolean {\n return Object.values(schema).every((model) => {\n const state: ModelState = model[\"~\"].state;\n return Object.values(state.scalars).every(\n (scalar) => scalar[\"~\"].state.schema === undefined\n );\n });\n}\n\n/** A filter list as one `where`. */\nconst filterOf = (items: readonly unknown[]): unknown =>\n items.length < 2 ? items[0] : { AND: items };\n\n/**\n * One extension's rule layer with every predicate admitted once, its tests\n * of an argument folded per call. Admitted once per schema registry, where\n * the schema's scalars admit with the engine's own schemas.\n */\nexport function admitLayer(\n layer: RuleLayer,\n schema: Schema,\n extension: string,\n given?: SchemaRegistryLookup<Schema>\n): AdmittedLayer {\n const registry = given ?? createSchemaRegistry(schema);\n // Refusals are `ClientInitializationError`s naming the extension, the\n // model, the predicate's place in the rule and the path inside it.\n const refuse = (name: string, place: string, reason: string): never => {\n throw new ClientInitializationError(\n `Extension \"${extension}\" rule.${place}: ${reason}.`,\n { meta: { extension, model: name } }\n );\n };\n /**\n * Shared sub-predicates are walked and parsed once per set of predicates\n * whose references are told apart: a reused parse makes no parameter, so\n * it records nothing.\n */\n const parsed = new Map<string, AdmittedFilters>();\n const admit = (\n name: string,\n place: string,\n predicate: unknown,\n references: References,\n of = \"\"\n ): Input => {\n const where = registry.getModelSchemas(schema[name]!).core.where;\n const at: Admitting = { references, schema, registry };\n const value = (word: unknown): object | undefined =>\n word instanceof PredicateWord ? word.value?.(at) : undefined;\n const filter = (word: object): FilterWord | undefined =>\n word instanceof PredicateWord ? word.filter?.(at) : undefined;\n const result = admittingDomainPredicate(\n { value, filter },\n () => validateSchema(where, predicate),\n memo(parsed, of, () => new WeakMap())\n );\n admitting.reads ??= at.reads;\n // The model's where schema admitted the predicate: an Input.\n if (!result.issues) return result.value as Input;\n const [issue] = result.issues;\n return refuse(\n name,\n place,\n `at \"${issue!.path?.map(String).join(\".\") || \"root\"}\": ${issue!.message}`\n );\n };\n const admitting: Admission = { schema, admit, refuse };\n const references: References = new Set();\n const models: Record<string, Filters> = {};\n /** One model's filters, each purpose's admitted. */\n const filtersOf: FiltersOf = (name, lists, read, of) => {\n const out: { root?: Input; related?: Input } = {};\n for (const purpose of [\"root\", \"related\"] as const) {\n const predicate = filterOf(lists[purpose] ?? []);\n if (predicate !== undefined)\n out[purpose] = admit(name, `${name}.${purpose}`, predicate, read, of);\n }\n return out;\n };\n for (const name of new Set([\n ...Object.keys(layer.root),\n ...Object.keys(layer.related),\n ]))\n models[name] = filtersOf(\n name,\n { root: layer.root[name], related: layer.related[name] },\n references,\n \"\"\n );\n const { host } = layer;\n const rules = host?.admit(admitting, layer, filtersOf, references) ?? {};\n const confine = layer.confine\n ? layer.brings!.confines!.admit(admitting, layer.confine, references)\n : undefined;\n const reads = layer.reads ?? admitting.reads;\n const out: AdmittedLayer = {\n extension,\n models,\n rules,\n ...(host && { host }),\n ...(reads && { reads }),\n ...(layer.brings && { brings: layer.brings }),\n ...(confine && { confine }),\n references: [...references],\n };\n return out;\n}\n","import type {\n CallRows,\n ModelDomain,\n RowDomain,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport { type Input, memo } from \"@query-engine/raptor3/shared/schema\";\nimport {\n type AdmittedLayer,\n admitLayer,\n type BoundEntries,\n nativeSchema,\n type RuleLayer,\n} from \"./admission\";\nimport { rebind, refuseUndeclared } from \"./call-rows\";\nimport type {\n CallRowsBinding,\n ExtensionPart,\n ResolvedExtensionChain,\n} from \"./chain\";\nimport { prepareCall } from \"./row-domain\";\n\n/**\n * One purpose's predicates per model, each at its layer's place in the\n * chain: the layer the engine reads it as.\n */\nfunction modelDomain(\n layers: readonly AdmittedLayer[],\n purpose: \"root\" | \"related\",\n lazy: BoundEntries[\"filters\"] | undefined\n): ModelDomain {\n const built = new Map<string, readonly Input[] | null>();\n return {\n get: (model) =>\n memo(built, model, () => {\n let list: Input[] | null = null;\n for (const [layer, member] of layers.entries()) {\n // An entry given lazily holds its filters: read it now.\n const filters = member.models[model] ?? lazy?.(model, layer);\n const where = filters?.[purpose];\n if (where !== undefined) (list ??= [])[layer] = where;\n }\n return list;\n }) ?? undefined,\n };\n}\n/**\n * A chain's row facts, resolved once when an extension is applied: one\n * domain, with the chain's kept rows, stamps and order, so a call only looks\n * its facts up. The predicates hold the values they read as parameters,\n * prepared once for every call: where one of them reads a call value, what\n * the words that read it brought carries each call's values beside the\n * shared domain (`call-values.ts`). Bound for a chain whose parts filter,\n * keep or judge rows.\n */\nexport function bindRows(chain: ResolvedExtensionChain): CallRowsBinding {\n // Only a rule's layer binds rows (`keep` comes with one).\n const layers = chain.rules!;\n // The entries beyond the filters, where some word brought what binds them.\n const host = layers.find((layer) => layer.host)?.host;\n const {\n lazy = false,\n filters,\n prepare = prepareCall,\n ...entries\n } = host?.bind(chain) ?? {};\n const { kept, stamps, defaultOrder: order } = chain;\n let domain: RowDomain = {\n root: modelDomain(layers, \"root\", filters),\n related: modelDomain(layers, \"related\", filters),\n ...entries,\n // Where some layer confines its sets, what `within` brought binds them.\n ...layers.find((layer) => layer.confine)?.brings?.confines?.bind(layers),\n ...(order && { order: new Map(Object.entries(order)) }),\n };\n // Where some predicate reads its call, what the words that read it\n // brought carries each call's values.\n const reads = layers\n .find((layer) => layer.reads)\n ?.reads?.bind(chain, lazy, domain);\n if (reads) domain = reads.domain;\n /** The facts of a call that deletes physically. */\n const physical: CallRows = {\n domain,\n ...(stamps && { stamps: stamps.all }),\n prepare,\n };\n /** The facts of a call whose deletes keep their rows. */\n const tombstoning =\n kept === undefined ? physical : { ...physical, tombstones: kept };\n return {\n /**\n * One call's row facts, from the arguments it admitted, and whether it\n * deletes physically ({@link Kept.removes}); when a stamp names an\n * argument, the call's values are put in.\n */\n call(model, values) {\n let facts =\n kept?.removes(model, values) === true ? physical : tombstoning;\n if (stamps?.named === true)\n facts = { ...facts, stamps: stamps.of(values) };\n return reads?.call(facts, values) ?? facts;\n },\n };\n}\n\n/**\n * `rule`: one extension's layer admitted where it is applied, the arguments\n * its predicates read checked against the chain's (an entry given lazily's\n * when it is first read), and the chain's call facts bound again. The layer\n * is the extension's for one schema: admitted once where the schema's\n * scalars admit with the engine's own schemas (a field's own schema may\n * read its value differently on another call).\n */\nexport function layerPart(layer: RuleLayer): ExtensionPart {\n let native: boolean | undefined;\n let admitted: AdmittedLayer | undefined;\n return {\n join(application) {\n const { name, next, schema, registry } = application;\n const own = admitted ?? admitLayer(layer, schema, name, registry);\n if ((native ??= nativeSchema(schema))) admitted = own;\n refuseUndeclared(application, own.references);\n next.rules = [...(next.rules ?? []), own];\n next.bindRows = bindRows;\n },\n seal(application) {\n rebind(application, bindRows);\n },\n };\n}\n","/**\n * The rows a model keeps where a call deletes them: what such a row takes\n * instead of going, and what it meets where the database would have refused\n * its removal (`keep`). The engine asks the call's tombstones; this module,\n * brought by `keep`, answers.\n */\nimport { assembleAdapterSelect } from \"@adapters/adapter-internals\";\nimport type { Schema } from \"@client/types\";\nimport type {\n PreparedDomain,\n PreparedPredicate,\n PreparedSelector,\n Queries,\n Query,\n} from \"@query-engine/raptor3/shared/query\";\nimport {\n COUNT_LEAF,\n newSelectorFacts,\n} from \"@query-engine/raptor3/shared/query\";\nimport type {\n Condition,\n Tombstones,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { EngineSchema, Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { SqlQueries } from \"@query-engine/raptor3/shared/sql-queries\";\nimport {\n bindMembership,\n type Membership,\n} from \"@query-engine/raptor3/shared/storage\";\nimport type { Writer } from \"@query-engine/raptor3/write/statements\";\nimport type { PreparedGuardFailure } from \"@query-engine/types\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { AnyRelation } from \"@schema/relation/types\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport { rebind, refuseUndeclared } from \"./call-rows\";\nimport type { ExtensionPart } from \"./chain\";\nimport { extensionError } from \"./chain\";\nimport { bindRows } from \"./rows\";\n\n/** Per managed model, what its deletes write instead, and who declared it. */\nexport class Kept extends Map<string, ResolvedKept> implements Tombstones {\n /**\n * Whether a delete of `model` removes its rows: its `keep` keeps them\n * where its test holds (`when`) or fails (`unless`), and the call's\n * arguments say otherwise, where its argument's `.on()` accepts it.\n */\n removes(model: string, values: AdmittedArgs | undefined): boolean {\n const kept = this.get(model);\n return (\n kept?.test !== undefined &&\n // Its test names an argument (`keep` refuses `now`): no instant.\n kept.test.holds({ args: values ?? {} }) !== kept.keeps\n );\n }\n marks(writer: Writer, model: AnyModel): Input | undefined {\n const { scope, schema } = writer.operation;\n const mark = this.get(model[\"~\"].names.ts!);\n if (!mark) return undefined;\n // A kept row is updated: it takes what every update of its model takes.\n return writer.values(\n model,\n \"update\",\n schema.update(\n model,\n mark.at === undefined\n ? mark.assign\n : { ...mark.assign, [mark.at]: scope!.instant() }\n ),\n {}\n );\n }\n referenced(\n schema: EngineSchema,\n edge: Membership | undefined,\n of?: Input\n ): true | { readonly slot: string; readonly identity: Input } {\n const slot =\n edge &&\n schema\n .restrictingSlots(edge.target)\n .find(\n (name) =>\n schema.index.get(edge.target)?.get(name)?.edge ===\n edge.scope.edge &&\n !(edge.target === edge.source && name === edge.name)\n );\n return slot ? { slot, identity: of! } : true;\n }\n restriction(\n schema: EngineSchema,\n model: AnyModel\n ): PreparedGuardFailure | undefined {\n const slots = schema.restrictingSlots(model);\n return slots.length > 0\n ? {\n kind: \"foreignKey\",\n message: `Cannot delete '${model[\"~\"].names.ts!}' record: a related record still references it through one of its relations whose foreign key restricts deletes: ${slots\n .map((slot) => `'${slot}'`)\n .join(\", \")}.`,\n raceable: false,\n }\n : undefined;\n }\n /**\n * Every row of `selector` locked, answered as ONE row: the inner read takes\n * the row locks (`FOR UPDATE`), and the count over it, which must consume\n * every row, is all that crosses the wire. Locking a million candidates\n * then costs one row back, not a million keys.\n */\n lock(queries: Queries, selector: PreparedSelector): Query {\n // Tombstones lock only on a SQL write: the engine hands its SqlQueries.\n const q = queries as SqlQueries;\n const a = q.adapter;\n const inner = q.rootAlias();\n const locked = assembleAdapterSelect(a, {\n columns: a.literals.true(),\n from: q.table(selector.model, inner),\n where: q.lowerSelector(selector, inner),\n forUpdate: true,\n });\n return {\n sql: assembleAdapterSelect(a, {\n columns: a.identifiers.aliased(a.aggregates.count(), \"_count\"),\n from: a.subqueries.correlate(locked, q.alias()),\n }),\n shape: { kind: \"object\", fields: { _count: COUNT_LEAF } },\n };\n }\n /**\n * The rows a hard delete meets the database's restrict on. A member is\n * visible when it satisfies its model's inputs in `visible`; one member may\n * be excepted by identity: the parent a nested delete keeps its link to,\n * whose own membership a hard delete removes first.\n */\n selector(\n queries: Queries,\n model: AnyModel,\n visible: PreparedDomain | undefined,\n except?: { readonly slot: string; readonly identity: Input }\n ): PreparedSelector {\n const predicates = queries.schema\n .restrictingSlots(model)\n .map((slot): PreparedPredicate => {\n const edge = bindMembership(queries.schema, model, slot);\n const arms: PreparedPredicate[] = [];\n const domain = visible?.selector(edge.target, \"related\")?.predicate;\n if (domain) arms.push(domain);\n if (except?.slot === slot)\n arms.push(\n queries.combine(\"NOT\", [\n // The member's own facts: a premise states them, nothing plans on them.\n queries.identityPredicate(\n edge.target,\n except.identity,\n newSelectorFacts(false)\n ),\n ])\n );\n // Visibility is the given domain's, never the lowering call's own.\n return {\n kind: \"relation\",\n edge,\n quantifier: \"some\",\n predicate:\n arms.length === 0 ? undefined : queries.combine(\"AND\", arms),\n unscoped: true,\n };\n });\n return {\n model,\n facts: newSelectorFacts(false),\n predicate: queries.combine(\"OR\", predicates),\n };\n }\n}\n\n/** The slot a model is the declared junction of, for a refusal to name. */\nfunction junctionHolder(schema: Schema, model: AnyModel) {\n for (const [holder, candidate] of Object.entries(schema))\n for (const [field, relation] of Object.entries(\n candidate[\"~\"].state.relations\n )) {\n // A model state types its relations loosely; each is a relation.\n const internal = (relation as AnyRelation)[\"~\"];\n if (\n internal.state.junction?.model !== undefined &&\n internal.settleJunctionModel!() === model\n )\n return `${holder}.${field}`;\n }\n return undefined;\n}\n\n/** What a delete of one model writes instead of removing the row, as `keep` writes it. */\ninterface KeptModel {\n /** The DateTime field that receives the call's one instant. */\n readonly at?: string;\n readonly assign: Readonly<Record<string, unknown>>;\n /**\n * `keep(when(…))` or `keep(unless(…))`: the test of an argument, and\n * whether the row is kept where it holds (`when`) or where it fails.\n * Without one, every delete keeps the row.\n */\n readonly test?: Condition;\n readonly keeps?: boolean;\n}\n\n/** What a delete of one managed model writes, and who declared it. */\nexport interface ResolvedKept extends KeptModel {\n readonly extension: string;\n}\n\n/**\n * Kept rows of one model, brought by its `keep`. A delete of a managed\n * model is an update, which every filter of the chain reads as it reads\n * any, so the filters' binding binds a chain that keeps rows; a later\n * entry for a model replaces one.\n */\nexport function keptPart(model: string, entry: KeptModel): ExtensionPart {\n return {\n join(application) {\n const { next, schema, name: extension } = application;\n refuseUndeclared(application, [entry.test?.parameter.arg]);\n const holder = junctionHolder(schema, schema[model]!);\n if (holder !== undefined)\n extensionError(\n `Extension \"${extension}\" rule.${model}.delete.instead: the model is the junction of '${holder}', so a kept link would still be followed. Delete the link with the relation's disconnect, or the row through its delegate.`,\n extension\n );\n const kept = new Kept(next.kept);\n kept.set(model, { extension, ...entry });\n next.kept = kept;\n next.bindRows = bindRows;\n },\n seal(application) {\n rebind(application, bindRows);\n },\n };\n}\n","/**\n * What a read of gated fields leaves to decoding: the fields a caller named,\n * marked at admission, and the document that leaves out or refuses what its\n * gates do not hold (K5). The engine decodes; `projection.ts` lowers.\n */\nimport { ValidationError } from \"@errors\";\nimport {\n BOOLEAN_LEAF,\n InvalidScalarResult,\n own,\n type ProjectionShape,\n providerDocument,\n providerJson,\n type Queries,\n type Reader,\n type ResultRefusal,\n} from \"@query-engine/raptor3/shared/query\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { Operation } from \"@query-engine/types\";\n\n/**\n * The selections a caller wrote, and the read-gated fields each names (K5):\n * admission marks them by identity, as `omit` and `include` desugar every\n * node into a `select` naming every scalar. A field a selection does not mark\n * is projected where its gate holds and left out elsewhere.\n */\nexport const namedGatedFields = new WeakMap<object, ReadonlySet<string>>();\nconst UNREADABLE = \"is not readable on a returned row\";\n/**\n * A row the read returned lacks the gate of a field the caller named (K5,\n * OD-5): raised while decoding, after the statement and before any result.\n */\nexport class GatedFieldRefusal extends Error implements ResultRefusal {\n readonly path: string;\n constructor(path: string) {\n super(`The selected field at '${path}' ${UNREADABLE}`);\n this.path = path;\n }\n /** The `ValidationError` of `operation`, at the path the caller named. */\n refusal(operation: Operation, model: string): ValidationError {\n return new ValidationError(\n operation,\n [{ path: this.path, message: UNREADABLE }],\n { meta: { model } }\n );\n }\n}\n/**\n * A document with read-gated members (K5), out of line from the plain\n * reader: its gates are read first, once per row, and each gated member is\n * written only where its gate holds; where it does not, a member the caller\n * named fails the read, and any other is left out (the row's shape\n * changes, so the document is always a new object).\n */\nexport function gatedDocument(\n q: Queries,\n carried: boolean,\n shape: Extract<ProjectionShape, { kind: \"object\" }>,\n fields: readonly string[],\n readers: readonly Reader[],\n columns?: readonly string[]\n): Reader {\n // Its gates read as `q` reads a boolean.\n const readGate = q.compileReader(BOOLEAN_LEAF, false, carried);\n const gates = shape.gates!;\n const gated = fields.map((field) => shape.gated![field]);\n const gateIndex = gated.map((member) =>\n member === undefined ? -1 : gates.indexOf(member.gate)\n );\n const positions = columns && [\n ...fields.map((field) => columns.lastIndexOf(field)),\n ...gates.map((gate) => columns.lastIndexOf(gate)),\n ];\n const cell = (source: unknown, index: number, key: string): unknown => {\n // Without columns a source row is a record, with them an array of cells.\n if (positions === undefined) return own(source as Input, key);\n // A column the statement does not carry is at -1, where no row has a cell.\n return (source as unknown[])[positions[index]!];\n };\n return (value) => {\n let source: unknown = value;\n // A positional row is an array: its driver asserted it. Only the count\n // carrier is never null, and it carries no gate.\n if (!positions) {\n source = providerDocument(providerJson(value));\n if (source === null) return null;\n if (source === undefined)\n throw new InvalidScalarResult(\n \"row\",\n \"a requested document is not a provider row\"\n );\n }\n const held = gates.map((gate, index) =>\n readGate(cell(source, fields.length + index, gate))\n );\n const document: Input = {};\n for (let index = 0; index < fields.length; index++) {\n const field = fields[index]!;\n const gate = gateIndex[index]!;\n if (gate >= 0 && held[gate] !== true) {\n const refused = gated[index]!.refused;\n if (refused !== undefined) throw new GatedFieldRefusal(refused);\n continue;\n }\n document[field] = readers[index]!(cell(source, index, field));\n }\n return document;\n };\n}\n","import type {\n Operation as Admitted,\n Arguments,\n EngineSchema,\n} from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { parseProviding } from \"@validation/primitives/object\";\nimport { namedGatedFields } from \"./gates\";\nimport type { Projection } from \"./projection\";\n\n/**\n * Projection keys a domain declares, admitted by the shared schema (K5).\n *\n * The `select` and `include` schemas are the schema's, shared by every chain\n * over it, and refuse a key they do not declare unless the parse adds it\n * under the model's name (`parseProviding`). So a call whose domain declares\n * a projection key is admitted inside a parse that adds that key, with its\n * own validator. What admission cannot say is which read-gated fields the\n * caller named, since the `select` it returns names every scalar of a node\n * an `include` or an `omit` spelled: those are read from the caller's\n * arguments and marked on the `select` admission returned.\n */\n\n/** The operations whose results are not rows: a projection reaches none. */\nconst NOT_ROWS: ReadonlySet<Admitted> = new Set<Admitted>([\n \"count\",\n \"exist\",\n \"aggregate\",\n \"groupBy\",\n]);\n\n/** A key's admitted value: `true`, nothing for `false`, or a list of the names it declares. */\nconst keyValidator =\n (names: readonly (readonly [string, unknown])[]) => (value: unknown) =>\n typeof value === \"boolean\"\n ? { value: value || undefined }\n : Array.isArray(value) &&\n value.length > 0 &&\n // A declared name is a string: no other value equals one.\n value.every((name) => names.some(([declared]) => declared === name))\n ? { value: [...value] }\n : {\n issues: [\n {\n message: `expected true, false or a list of ${names.map(([name]) => name).join(\", \")}`,\n },\n ],\n };\n\n/**\n * Mark, on each node admission returned, the read-gated fields the caller\n * named on that node: walked beside the caller's arguments, container by\n * container, as admission keeps them.\n */\nfunction markNamed(\n domain: Projection,\n schema: EngineSchema,\n model: AnyModel,\n raw: unknown,\n admitted: unknown\n): void {\n if (!(isPlainRecord(raw) && isPlainRecord(admitted))) return;\n const select = isPlainRecord(raw.select) ? raw.select : undefined;\n const omit = isPlainRecord(raw.omit) ? raw.omit : undefined;\n const named = new Set<string>();\n for (const field of domain.projected(model)?.gates.keys() ?? [])\n if (\n select\n ? select[field] === true && omit?.[field] !== true\n : omit?.[field] === false\n )\n named.add(field);\n if (named.size > 0 && isPlainRecord(admitted.select))\n namedGatedFields.set(admitted.select, named);\n for (const container of [\"select\", \"include\"] as const) {\n const given = raw[container];\n const kept = admitted[container];\n if (!(isPlainRecord(given) && isPlainRecord(kept))) continue;\n for (const name of Object.keys(given)) {\n const resolved = model[\"~\"].state.relations[name]\n ? schema.index.get(model)?.get(name)\n : undefined;\n if (resolved === undefined) continue;\n const many = resolved.edge.kind === \"variantJunctionCarrier\";\n // A polymorphic relation's arms, each under its variant (a\n // junction's under `variants`); any other relation is one arm.\n const variants =\n resolved.member || !(many || resolved.edge.kind === \"variantRowCarrier\")\n ? [undefined]\n : resolved.edge.members.map(({ variant }) => variant);\n const arm = (node: unknown, variant: string | undefined) => {\n if (variant === undefined) return node;\n const arms = isPlainRecord(node) && many ? node.variants : node;\n return isPlainRecord(arms) ? arms[variant] : undefined;\n };\n for (const variant of variants)\n markNamed(\n domain,\n schema,\n schema.membership(model, name, variant).target,\n arm(given[name], variant),\n arm(kept[name], variant)\n );\n }\n }\n}\n\n/**\n * `raw` admitted by the schema with the projection keys of the domain added\n * to the schema's, and the read-gated fields it names marked: as the schema\n * admits it where the call reads no rows. The projection's `admit`, called\n * on it.\n */\nexport function admitProjected(\n this: Projection,\n schema: EngineSchema,\n model: AnyModel,\n operation: Admitted,\n raw: unknown\n): Arguments {\n const admit = () => schema.admit(model, operation, raw);\n // The model's entries are read before its arguments: an entry given\n // lazily refuses the call first.\n this.projected(model);\n if (NOT_ROWS.has(operation)) return admit();\n // A projection is provided under `$` and its model's name.\n const admitted = parseProviding((name, key) => {\n const target = name[0] === \"$\" ? schema.schema[name.slice(1)] : undefined;\n const declared = target && this.projected(target)?.keys.get(key);\n return declared && keyValidator(declared.names);\n }, admit);\n markNamed(this, schema, model, raw, admitted);\n return admitted;\n}\n","/**\n * What a read carries beside its rows and what it hides of them, for one\n * prepared domain: the entries' projection keys (`evidence`) and read-gated\n * fields (`reads`). A field a rule hides reads NULL where its row does not\n * carry it, and a declared key says which rules hold of a row. Brought by\n * `gate` and `facts`: a program whose rules neither gate nor report holds\n * none of it. The engine lowers the predicates and decodes the rest.\n */\nimport { assembleAdapterSelect } from \"@adapters/adapter-internals\";\nimport { ClientInitializationError, UnsupportedOperationError } from \"@errors\";\nimport {\n BOOLEAN_LEAF,\n type DeclaredEvidence,\n type FieldGate,\n type GatedMember,\n type Leaf,\n type PreparedProjection,\n type PreparedProjectionField,\n type PreparedSelector,\n type ProjectedFacts,\n type Shape,\n} from \"@query-engine/raptor3/shared/query\";\nimport type { JudgedEntry } from \"@query-engine/raptor3/shared/row-scope\";\nimport { type Input, memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { SqlQueries } from \"@query-engine/raptor3/shared/sql-queries\";\nimport type { Membership } from \"@query-engine/raptor3/shared/storage\";\nimport { listed } from \"@query-engine/raptor3/shared/terms\";\nimport { gateResultKey } from \"@query-engine/result-aliases\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport { ALL } from \"./entries\";\nimport { gatedDocument, namedGatedFields } from \"./gates\";\nimport { admitProjected } from \"./projected\";\nimport type { PreparedDomain } from \"./row-domain\";\n\n/**\n * One model's projection keys across a chain's layers, brought by `facts`:\n * one key, one layer, since a second would hide the first, and never a\n * relation's link row's name.\n */\nexport function refuseSharedKeys(\n model: string,\n layers: readonly (JudgedEntry | undefined)[]\n): void {\n const keys = new Set<string>();\n for (const layer of layers) {\n const key = layer?.as;\n if (key === undefined) continue;\n if (key === \"$through\" || keys.has(key))\n throw new ClientInitializationError(\n `rule.${model}.read.select \"${key}\" ${key === \"$through\" ? \"is reserved for a relation's link row\" : \"is declared by two extensions of the chain\"}.`,\n { meta: { model } }\n );\n keys.add(key);\n }\n}\n\n/** What the engine asks of what projects and hides a domain's fields. */\nexport type Projection = ReturnType<typeof projectionOf>;\n\n/** What projects and hides fields, for one domain: brought by `gate` and `facts`. */\nexport const projectionOf = (domain: PreparedDomain) => {\n const projectedBy = new Map<string, ProjectedFacts | null>();\n const layeredBy = new Map<string, Map<Input, PreparedSelector>>();\n /**\n * The default projections of the models this domain projects facts for:\n * theirs differ from the view's shared ones, which carry no gate.\n */\n const defaultProjections = new WeakMap<AnyModel, PreparedProjection>();\n /**\n * Where `input`, one of `model`'s predicates in `layer`, holds on the row\n * at `alias`, as that layer's node: R5 and R6 judge it as they judge the\n * layer's filter. `undefined` where the call drops it (it holds).\n */\n const layerHolds = (\n q: SqlQueries,\n model: AnyModel,\n layer: number,\n input: Input,\n alias?: string\n ): Sql | undefined =>\n q.lowerSelector(projection.layered(model, layer, input), alias);\n /** `model`'s read-gated fields, each with its gate. */\n const gatesOf = (model: AnyModel) => projection.projected(model)?.gates;\n /** Where a read-gated field's row carries it: every gating layer's `read` and predicate. */\n function gateHolds(\n q: SqlQueries,\n model: AnyModel,\n gate: FieldGate,\n alias: string | undefined,\n visible: boolean\n ): Sql | undefined {\n const held: Sql[] = [];\n // A gate masks a value: neither a positive nor a negative test, so no\n // set it reads is bounded ({@link setBound}) and it holds where it would.\n q.unbounded++;\n try {\n for (const [layer, read, input] of gate) {\n const tested = input === read ? [read] : [read, input];\n for (const where of visible ? tested.slice(1) : tested) {\n const lowered = layerHolds(q, model, layer, where, alias);\n if (lowered !== undefined) held.push(lowered);\n }\n }\n } finally {\n q.unbounded--;\n }\n return held.length === 0 ? undefined : q.adapter.operators.and(...held);\n }\n const projection = {\n /**\n * A projection key's value, or whether a gated field's row carries it, on\n * the row at `alias` (`taken`: a row the domain already took). A key's\n * value is the layer's `read` once, around a document of one boolean per\n * name (K5).\n */\n lower(\n q: SqlQueries,\n model: AnyModel,\n field: Extract<PreparedProjectionField, { kind: \"evidence\" | \"gate\" }>,\n alias: string | undefined,\n taken: boolean\n ): Sql {\n if (field.kind === \"gate\")\n return q.truth(gateHolds(q, model, field.gate, alias, taken));\n const a = q.adapter;\n const { layer, read } = field.evidence;\n const visible = taken\n ? undefined\n : layerHolds(q, model, layer, read, alias);\n const held = a.json.objectFromColumns(\n field.names.map(([name, input]) => [\n name,\n q.truth(\n input === read\n ? undefined\n : layerHolds(q, model, layer, input, alias)\n ),\n ])\n );\n return visible === undefined\n ? held\n : a.expressions.caseWhen(\n [{ when: visible, then: held }],\n a.json.objectFromColumns(\n field.names.map(([name]) => [name, a.literals.false()])\n )\n );\n },\n /**\n * A read-gated model's rows `where` keeps, as a window whose gated\n * columns read NULL on a row that does not carry them (K5), for a group\n * read: each gate lowered once per row, where a gate repeated in the\n * grouping, the projection and the order would be three expressions to\n * the provider. `undefined` where the model gates nothing.\n */\n window(\n q: SqlQueries,\n model: AnyModel,\n where: Input | undefined\n ): Sql | undefined {\n if (!gatesOf(model)?.size) return undefined;\n const a = q.adapter;\n const inner = q.alias();\n return assembleAdapterSelect(a, {\n columns: listed(\n q.schema\n .storedFields(model)\n .map((field) =>\n a.identifiers.aliased(\n projection.guarded(\n q,\n model,\n field,\n q.column(model, field, inner),\n inner\n ),\n q.columnName(model, field)\n )\n )\n ),\n from: q.table(model, inner),\n where: q.lowerWhere(model, where, inner),\n });\n },\n gatedDocument,\n /**\n * `column`, `model`'s `field` at `alias`, as an operand the caller wrote\n * (K5): NULL on a row that does not carry a read-gated field. Every row a\n * caller's operand is read on is one the domain takes, so `read` holds\n * there: the gate's own predicate decides.\n */\n guarded(\n q: SqlQueries,\n model: AnyModel,\n field: string,\n column: Sql,\n alias?: string\n ): Sql {\n const gate = gatesOf(model)?.get(field);\n const holds = gate && gateHolds(q, model, gate, alias, true);\n const a = q.adapter;\n return holds === undefined\n ? column\n : a.expressions.caseWhen(\n [{ when: holds, then: column }],\n a.literals.null()\n );\n },\n /**\n * A call's arguments admitted with the projection keys this domain\n * declares kept beside the schema's.\n */\n admit: admitProjected,\n /**\n * A `$through` that reads or tests a gated field of its junction `model`\n * is refused before any statement, as a hidden link row is: the hop has no\n * faithful answer for a field its reader may not see.\n */\n refuseGatedLink(\n edge: Membership,\n model: AnyModel,\n fields: readonly string[],\n use: \"read\" | \"filter\"\n ): void {\n const gates = gatesOf(model);\n const gated = gates && fields.find((field) => gates.has(field));\n const name = model[\"~\"].names.ts;\n if (gated !== undefined)\n throw new UnsupportedOperationError(\n `Cannot ${use} $through.${gated} of relation '${edge.name}': this client gates that field of '${name}'. Read it through the '${name}' delegate.`\n );\n },\n /** `$rows()` hands a caller the table's columns as they are: refused where a field of them is read-gated. */\n refuseGatedRows(model: AnyModel): void {\n const gates = gatesOf(model);\n if (gates?.size)\n throw new UnsupportedOperationError(\n `${model[\"~\"].names.ts}.$rows() refuses read-gated fields: ${[...gates.keys()]}`\n );\n },\n /** `input`, one of `model`'s predicates in `layer`, as that layer's node. */\n layered(model: AnyModel, layer: number, input: Input): PreparedSelector {\n const name = model[\"~\"].names.ts!;\n const inputs = memo(layeredBy, `${name} ${layer}`, () => new Map());\n return memo(\n inputs,\n input,\n () => domain.conjunction(model, [[layer, [input]]])!\n );\n },\n /**\n * `model`'s projection keys and read-gated fields, equal gates shared so\n * a projection carries one member per distinct gate; `undefined` for\n * none.\n */\n projected(model: AnyModel): ProjectedFacts | undefined {\n const name = model[\"~\"].names.ts!;\n const projected = memo(projectedBy, name, () => {\n const keys = new Map<string, DeclaredEvidence>();\n const gates = new Map<string, FieldGate>();\n for (const [layer, entry] of (\n domain.rows.rules?.get(name) ?? []\n ).entries()) {\n if (entry === undefined) continue;\n const { as, facts } = entry;\n const read = entry.shown ?? entry.read ?? ALL;\n if (as !== undefined)\n keys.set(as, { layer, read, names: [...facts!] });\n for (const [field, input] of entry.reads ?? [])\n gates.set(field, [\n ...(gates.get(field) ?? []),\n [layer, read, input] as const,\n ]);\n }\n const known: FieldGate[] = [];\n for (const [field, gate] of gates) {\n const same = known.find(\n (other) =>\n other.length === gate.length &&\n other.every(\n ([layer, , input], index) =>\n layer === gate[index]![0] && input === gate[index]![2]\n )\n );\n if (same === undefined) known.push(gate);\n gates.set(field, same ?? gate);\n }\n return keys.size === 0 && gates.size === 0 ? null : { keys, gates };\n });\n return projected ?? undefined;\n },\n /**\n * What this domain adds to one projection of `model` a caller reads (K5),\n * `undefined` where it declares neither key nor gate on the model: the\n * default projections it shares, its declared keys (`key`: whether `name`\n * is one, projected: `true` reports every declared name, a list the names\n * it gives, in declared order, one boolean per name), and each gate of a\n * scalar it reads (`field`, after the scalar: projected once), with the\n * shape that says which member decides each gated field, and which of\n * them the caller named.\n */\n preparing(model: AnyModel, select: unknown, path: string) {\n const projected = projection.projected(model);\n if (projected === undefined) return undefined;\n // The engine hands an admitted `select`, an object, or none, which no\n // entry is keyed by.\n const named = namedGatedFields.get(select as object);\n const gated: Record<string, GatedMember> = {};\n const gates = new Map<FieldGate, string>();\n return {\n defaults: defaultProjections,\n key: (\n name: string,\n selection: unknown,\n fields: Record<string, Shape | Leaf>,\n prepared: PreparedProjectionField[]\n ): boolean => {\n const evidence = projected.keys.get(name);\n if (evidence === undefined) return false;\n const names =\n selection === true\n ? evidence.names\n : evidence.names.filter(([held]) =>\n // Admission left `true` or a list of the declared names.\n (selection as readonly string[]).includes(held)\n );\n fields[name] = {\n kind: \"object\",\n nullable: false,\n fields: Object.fromEntries(\n names.map(([held]) => [held, BOOLEAN_LEAF])\n ),\n };\n prepared.push({ kind: \"evidence\", name, evidence, names });\n return true;\n },\n field(name: string, prepared: PreparedProjectionField[]): void {\n const gate = projected.gates.get(name);\n if (gate === undefined) return;\n let member = gates.get(gate);\n if (member === undefined) {\n member = gateResultKey(gates.size);\n gates.set(gate, member);\n prepared.push({ kind: \"gate\", name: member, gate });\n }\n gated[name] = named?.has(name)\n ? { gate: member, refused: `${path}select.${name}` }\n : { gate: member };\n },\n shape: () =>\n gates.size > 0 ? { gated, gates: [...gates.values()] } : undefined,\n };\n },\n };\n return projection;\n};\n","/**\n * `rule({ [model]: entry })`: what binds every caller of a model, per model.\n * The leaves are the ORM's own `where`, checked once where the extension is\n * applied by the model's `where` schema (`admission.ts`), with the words of\n * `rule-words.ts` where a value or a filter goes. The part reads the keys it\n * owns, the filters by role and the confinements; every other value is a\n * word that carries what applies it (`judge-words.ts`), which rows a write\n * may take and an entry given lazily included, called where it is written\n * and never named here.\n */\nimport type { Schema } from \"@client/types\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport type { EntryDraft, RuleLayer } from \"./admission\";\nimport { type ExtensionPart, extensionError, shared } from \"./chain\";\nimport type {\n AnyTarget,\n ExactEntries,\n FromSchema,\n ModelName,\n Part,\n RuleFacts,\n RuleInput,\n} from \"./contract\";\nimport { layerPart } from \"./rows\";\nimport { CarriedValue, type Site } from \"./rule-words\";\n\ntype Entry = Readonly<Record<string, unknown>>;\n\nconst RULE_KEYS = new Set([\n \"read\",\n \"root\",\n \"related\",\n \"create\",\n \"update\",\n \"delete\",\n \"acyclic\",\n \"confine\",\n]);\n\nconst own = (value: unknown): Entry => (isPlainRecord(value) ? value : {});\n/** A filter list as written, copied: one filter or several. */\nexport const listOf = (value: unknown): unknown[] =>\n value === undefined ? [] : Array.isArray(value) ? [...value] : [value];\n\n/**\n * One entry's keys beyond its filters as a draft: each word joined where it\n * is written, anything else in a word's place refused; `undefined` where it\n * holds none. Inside an entry given lazily (`lazy`), its `read.where` is one\n * of them.\n */\nexport function draftOf(\n entry: unknown,\n model: string,\n schema: Schema,\n { layer, bring }: Pick<Site, \"layer\" | \"bring\">,\n refuse: (problem: string) => never,\n lazy: boolean\n): EntryDraft | undefined {\n let draft: EntryDraft | undefined;\n const read = own(own(entry).read);\n /**\n * Each word of `value`, at `key`, joined where it stands; anything else in\n * a word's place refused. A container (`create`, `update`, `delete`,\n * `update.fields` and each field of it, `read.fields`, `read.select`)\n * holds the places.\n */\n const join = (\n value: unknown,\n key: string,\n field?: string,\n container = false\n ): void => {\n if (value === undefined) return;\n if (value instanceof CarriedValue) {\n value.join({\n model,\n key,\n field,\n schema,\n layer,\n bring,\n lazy,\n // What a row a write returns holds for what a read carries to show.\n ...(!lazy && { shows: read.where }),\n entry: () => (draft ??= {}),\n refuse,\n });\n return;\n }\n if (!(container && isPlainRecord(value)))\n refuse(\n container\n ? `${key} is an object`\n : `${key} is written ${key.endsWith(\"where\") ? \"only(where)\" : \"with a word\"}`\n );\n // `fields` and `select` name a field, which every word below them reads.\n const names = key.endsWith(\"fields\") || key.endsWith(\"select\");\n for (const [name, item] of Object.entries(value))\n join(\n item,\n `${key}.${name}`,\n names ? name : field,\n key === \"update.fields\" || name === \"fields\"\n );\n };\n // `lazy(() => entry)`: it brings what reads the entry later.\n if (entry instanceof CarriedValue) {\n join(entry, \"the entry\");\n return;\n }\n if (!isPlainRecord(entry))\n return refuse(\n typeof entry === \"function\"\n ? \"an entry given as a function is written lazy(() => entry)\"\n : \"an entry is an object\"\n );\n for (const key of Object.keys(entry))\n if (!RULE_KEYS.has(key)) refuse(`\"${key}\" is not a rule key`);\n if (lazy && read.where !== undefined) (draft ??= {}).read = read.where;\n join(entry.confine, \"confine\");\n join(read.fields, \"read.fields\", undefined, true);\n join(read.select, \"read.select\", undefined, true);\n for (const key of [\"create\", \"update\", \"delete\"])\n join(entry[key], key, undefined, true);\n const { acyclic } = entry;\n if (acyclic !== undefined) {\n // A loop is refused where the row an update produces is judged; what\n // the list names is checked where it is admitted (`cyclesOf`).\n if (draft?.judge === undefined) refuse(\"acyclic needs a check() beside it\");\n draft.acyclic = acyclic;\n }\n return draft;\n}\n\n/** One extension's rule layer as its `rule` parts write it, and the parts its words bring. */\ninterface ExtensionLayer {\n readonly layer: RuleLayer;\n readonly brought: Set<ExtensionPart>;\n}\n\n/** The key an extension's `rule` parts meet at: its one layer. */\nconst LAYER: object = Object.freeze({});\n\n/** One rule part's entries, written on its extension's layer. */\nfunction writeRule(\n name: string,\n { layer, brought }: ExtensionLayer,\n entries: Entry,\n schema: Schema\n): void {\n const bring = (part: ExtensionPart): void => {\n brought.add(part);\n };\n for (const [model, entry] of Object.entries(entries)) {\n if (!Object.hasOwn(schema, model))\n extensionError(\n `Extension \"${name}\" rule names unknown model \"${model}\".`,\n name\n );\n const refuse = (problem: string): never =>\n extensionError(`Extension \"${name}\" rule.${model}: ${problem}.`, name);\n const draft = draftOf(\n entry,\n model,\n schema,\n { layer, bring },\n refuse,\n false\n );\n const written = own(entry);\n const { where } = own(written.read);\n for (const purpose of [\"root\", \"related\"] as const) {\n const items = listOf(written[purpose]);\n if (where !== undefined) items.unshift(where);\n if (items.length > 0)\n layer[purpose][model] = [...(layer[purpose][model] ?? []), ...items];\n }\n if (draft !== undefined) {\n if (Object.hasOwn(layer.rules, model))\n refuse(\"two rule parts of one extension judge the model\");\n layer.rules[model] = draft;\n }\n }\n}\n\n/**\n * What binds every caller of the models named: filters, checks, gated\n * fields, projections and kept rows. Given a function of the schema, it is\n * read where the extension is applied (an extension that depends on the\n * schema is written apart from any client).\n */\nexport function rule<T extends AnyTarget, const R = RuleInput<T>>(\n rules: R &\n (RuleInput<T> | FromSchema<T, RuleInput<T>>) &\n NoInfer<ExactEntries<R, RuleInput<T>>>\n): Part<T, RuleFacts<R, ModelName<T>>>;\nexport function rule(rules: Entry | ((schema: Schema) => Entry)): unknown {\n const part: ExtensionPart = {\n // Every rule part of one extension writes its one layer, once per\n // schema; the layer's own part admits it, and the parts its words\n // brought run with it.\n declare(application) {\n const { name, schema } = application;\n const own = shared(application, LAYER, (): ExtensionLayer => {\n const layer: RuleLayer = {\n root: {},\n related: {},\n rules: {},\n };\n return { layer, brought: new Set([layerPart(layer)]) };\n });\n shared(application, part, () =>\n writeRule(\n name,\n own,\n typeof rules === \"function\" ? rules(schema) : rules,\n schema\n )\n );\n for (const brought of own.brought) application.bring(brought);\n },\n };\n return part;\n}\n","/**\n * The words of a rule that judge or project rows: `only` (which rows a\n * write may take), `check` (the row a write leaves must hold a predicate),\n * `gate` (a field is present only where a predicate holds), `facts` (per\n * row, which named predicates hold, under a projection key), `keep` (a\n * delete updates the row instead) and `lazy` (an entry read when its model\n * is first read). Each carries what applies it, so a rule that only filters\n * holds none of it.\n */\nimport { Condition } from \"@query-engine/raptor3/shared/row-scope\";\nimport type { AnyModel } from \"@schema/model\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport type {\n AdmittedEntry,\n EntryDraft,\n LazyDraft,\n References,\n} from \"./admission\";\nimport { CALL_READS } from \"./call-values\";\nimport { extensionError } from \"./chain\";\nimport type {\n CheckWord,\n FactsWord,\n GateWord,\n HeldOperand,\n IsHeld,\n KeepWord,\n LazyWord,\n OnlyWord,\n} from \"./contract\";\nimport { admitDraft, ENTRIES, entryOf, prepareJudged } from \"./entries\";\nimport { judgeOf } from \"./judge\";\nimport { keptPart } from \"./kept\";\nimport { projectionOf, refuseSharedKeys } from \"./projection\";\nimport { draftOf, listOf } from \"./rule\";\nimport { CarriedValue, PredicateWord, type Site, testOf } from \"./rule-words\";\nimport { NOW } from \"./stamps\";\n\n/** A word written with one value, which its `join` reads. */\nexport abstract class Held<T> extends CarriedValue {\n readonly held: T;\n constructor(held: T) {\n super();\n this.held = held;\n }\n}\n\n/** What the layer of a word's site brings beside its filters. */\nconst brings = (site: Site) => (site.layer!.brings ??= {});\n\n/**\n * Where `only` or `check` writes its predicate in `own`, the entry of its\n * site: the entry key `places` gives the site's key, or, at\n * `update.fields.f.<…>` (`perField`), field `f` of the map `fields`,\n * refused where the model has no field so named.\n */\nfunction placed(\n { schema, model, key, field, refuse }: Site,\n own: EntryDraft,\n held: object,\n word: string,\n places: Readonly<Record<string, \"update\" | \"delete\" | \"place\" | \"check\">>,\n perField: RegExp,\n fields: \"writes\" | \"moves\"\n): void {\n const { state } = schema[model]![\"~\"];\n const at = places[key];\n if (at !== undefined) own[at] = held;\n else if (!perField.test(key)) refuse(`${key} does not take ${word}()`);\n else if (\n Object.hasOwn(state.scalars, field!) ||\n Object.hasOwn(state.relations, field!)\n )\n (own[fields] ??= new Map()).set(field!, held);\n else refuse(`update.fields names unknown field \"${field}\"`);\n}\n\n/**\n * The entry of a word that carries or hides fields of a read, with what\n * projects them.\n */\nfunction shown(site: Site) {\n const own = entryOf(site);\n own.shown = site.shows;\n brings(site).project = projectionOf;\n return own;\n}\n\nconst FIELD_WHERE = /^update\\.fields\\.[^.]+\\.where$/;\nconst FIELD_CHECK = /^update\\.fields\\.[^.]+\\.check$/;\n\n/** `only(where)`'s value: the rows a write may take. */\nclass Only extends Held<object> {\n join(site: Site): void {\n const own = entryOf(site);\n brings(site).prepare = prepareJudged;\n // An update writing the field takes its own instead of `update.where`.\n placed(\n site,\n own,\n this.held,\n \"only\",\n { \"update.where\": \"update\", \"delete.where\": \"delete\" },\n FIELD_WHERE,\n \"writes\"\n );\n }\n}\n\n/**\n * A write takes only the rows that hold `where`. Written apart from a rule\n * (a shared constant), nothing types its operand: any filter, which the\n * rule's model admits where it is applied (as for `check`).\n */\nexport function only<W>(\n where: HeldOperand<W>\n): IsHeld<W> extends true ? OnlyWord<never> : OnlyWord<W>;\nexport function only(where: object): unknown {\n return new Only(where);\n}\n\n/** `check(where)`'s value: what the row a write produces must hold. */\nclass Checked extends Held<object> {\n join(site: Site): void {\n const own = entryOf(site);\n own.judge = judgeOf;\n brings(site).judge = judgeOf;\n // The row an update leaves is judged again where the update writes a\n // field the predicate reads (`update.check`), or the field named.\n placed(\n site,\n own,\n this.held,\n \"check\",\n { \"create.check\": \"place\", \"update.check\": \"check\" },\n FIELD_CHECK,\n \"moves\"\n );\n }\n}\n\n/**\n * The row a write leaves (or creates) must hold `where`. Written apart from\n * a rule (a shared constant), nothing types its operand: it is a check of\n * any filter, which the rule's model admits where it is applied.\n */\nexport function check<W>(\n where: HeldOperand<W>\n): IsHeld<W> extends true ? CheckWord<never> : CheckWord<W>;\nexport function check(where: object): unknown {\n return new Checked(where);\n}\n\n/**\n * Whether `field` is one of the model's key, unique or foreign-key fields:\n * what identity and every join read, and what a unique constraint answers\n * for on a write, so none of them is ever read-gated. A write of a guessed\n * value fails on the constraint exactly when some row holds it: a gate on a\n * unique field would be confirmed by it, and a unique index, whole or\n * partial, is such a constraint.\n */\nconst isKeyField = (model: AnyModel, field: string): boolean =>\n getModelKeyCatalog(model).uniqueOverlapFields.includes(field) ||\n model[\"~\"].state.indexes.some(\n (index) => index.options.unique && index.fields.includes(field)\n ) ||\n Object.values<AnyRelation>(model[\"~\"].state.relations).some(\n (relation) =>\n relation[\"~\"].state.foreignKey?.fields.includes(field) === true\n );\n\n/** `gate(where)`'s value: where a field is present. */\nclass Gated extends Held<object> {\n join(site: Site): void {\n const { key, field, model, schema, refuse } = site;\n if (key !== `read.fields.${field}`) refuse(`${key} does not take gate()`);\n const held = schema[model]!;\n if (!Object.hasOwn(held[\"~\"].state.scalars, field!))\n refuse(`${key} names no scalar of the model`);\n // Masked in a caller's operands while identity and joins read it raw,\n // a key would answer through a relation what a filter hides.\n if (isKeyField(held, field!))\n refuse(`${key} names a key, a unique or a foreign key field`);\n (shown(site).reads ??= new Map()).set(field!, this.held);\n }\n}\n\n/**\n * The field is present where `where` holds, absent elsewhere, and read as\n * `NULL` by every operand a call writes over it.\n */\nexport function gate<W>(\n where: HeldOperand<W>\n): IsHeld<W> extends true ? GateWord<never> : GateWord<W>;\nexport function gate(where: object): unknown {\n return new Gated(where);\n}\n\n/**\n * A declared projection key's spelling: `$` and an identifier. No model\n * member and no engine carrier is spelled so, so a key never hides either,\n * whatever the schema later adds.\n */\nconst PROJECTION_KEY = /^\\$[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/** `facts({ … })`'s value: per row, which named predicates hold. */\nclass Facts extends Held<Readonly<Record<string, object>>> {\n join(site: Site): void {\n const { key, field, refuse } = site;\n if (key !== `read.select.${field}`) refuse(`${key} does not take facts()`);\n if (!PROJECTION_KEY.test(field!))\n refuse(`${key} is not \\`$\\` and an identifier`);\n const own = shown(site);\n if (own.as !== undefined) refuse(\"read.select holds one projection key\");\n brings(site).keys = refuseSharedKeys;\n own.as = field;\n own.facts = new Map(Object.entries(this.held));\n }\n}\n\n/**\n * Per row, whether each named predicate holds: a `select` or `include`\n * naming the key reads them.\n */\nexport function facts<const Names extends string>(\n predicates: Readonly<Record<Names, object>>\n): FactsWord<Names, false>;\nexport function facts(predicates: Readonly<Record<string, object>>): unknown {\n return new Facts(predicates);\n}\n\n/** `keep(data)`'s value: what a delete of the model writes instead. */\n// Not a `Held`: written alone (`viborm/soft-delete`), its own field weighs less.\nclass Kept extends CarriedValue {\n readonly data: unknown;\n constructor(data: unknown) {\n super();\n this.data = data;\n }\n join({ key, model, schema, lazy, bring, refuse: given }: Site): void {\n // Typed where it is declared, so a refusal narrows what follows it.\n const refuse: (problem: string) => never = given;\n // What a delete keeps is bound with the chain, before a lazy entry is read.\n if (key !== \"delete.instead\" || lazy)\n refuse(`${lazy ? \"a lazy entry\" : key} does not take keep()`);\n let data = this.data;\n // `keep(when(…))`, `keep(unless(…))`: kept where its test says, per call.\n const chosen =\n data instanceof PredicateWord && data.kind !== \"provided\"\n ? data\n : undefined;\n let test: Condition | undefined;\n if (chosen?.arg !== undefined) {\n const tested = testOf(chosen.test);\n if (typeof tested === \"string\") refuse(tested);\n test = new Condition(chosen.arg.stamp(), tested);\n data = chosen.then;\n }\n if (!isPlainRecord(data))\n refuse(\"keep() takes the data the row is updated with\");\n const { state } = schema[model]![\"~\"];\n let at: string | undefined;\n const assign: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(data)) {\n if (!Object.hasOwn(state.scalars, field))\n refuse(`keep() names unknown field \"${field}\"`);\n if (!(value instanceof PredicateWord)) assign[field] = value;\n else if (value.stamp?.() !== NOW || at !== undefined)\n refuse(\"keep() writes constants, and now in one field\");\n else at = field;\n }\n bring(\n keptPart(model, {\n ...(at !== undefined && { at }),\n assign,\n ...(test && { test, keeps: chosen!.kind === \"when\" }),\n })\n );\n }\n}\n\n/** The delete updates the row with `data` instead of removing it. */\nexport function keep<D>(data: D): KeepWord<D>;\nexport function keep(data: object): unknown {\n return new Kept(data);\n}\n\n/** `lazy(() => entry)`'s value: an entry read when its model is first read. */\nclass Lazy extends Held<() => unknown> {\n join(site: Site): void {\n const { key, model, schema, lazy, refuse } = site;\n if (key !== \"the entry\" || lazy) refuse(`${key} does not take lazy()`);\n const layer = site.layer!;\n // Called as a plain function, as written.\n const { held } = this;\n if (Object.hasOwn(layer.rules, model))\n refuse(\"two rule parts of one extension judge the model\");\n layer.host = ENTRIES;\n // What the entry reads of its call, and whether its words judge or\n // project, are known once it is read.\n layer.reads = CALL_READS;\n layer.brings = {\n judge: judgeOf,\n project: projectionOf,\n prepare: prepareJudged,\n keys: refuseSharedKeys,\n lazy: true,\n };\n // Admitted once, the first time its model is read, with its own\n // references, checked then against what each chain declared up to its\n // extension, as `$extends` checks an eager entry's.\n const read: LazyDraft = (admission, filtersOf) => {\n let admitted: AdmittedEntry | undefined;\n return (chain, extension) => {\n if (admitted === undefined) {\n const given: unknown = held();\n const written: Readonly<Record<string, unknown>> = isPlainRecord(\n given\n )\n ? given\n : {};\n const own: References = new Set();\n const at = `lazy ${model}`;\n const draft = draftOf(given, model, schema, site, refuse, true);\n const entry = admitDraft(admission, model, draft ?? {}, own, at);\n entry.filters = filtersOf(\n model,\n { root: listOf(written.root), related: listOf(written.related) },\n own,\n at\n );\n // Read after the filters: what they name is the entry's too.\n entry.references = [...own];\n admitted = entry;\n }\n // Declared by its own extension or one applied before it.\n const at = (name: string) =>\n chain.extensions.findIndex((member) => member.name === name);\n for (const name of admitted.references!)\n if (\n name !== undefined &&\n !chain.args?.all.some(\n (argument) =>\n argument.name === name &&\n at(argument.extension) <= at(extension)\n )\n )\n extensionError(\n `Extension \"${extension}\" references undeclared argument \"${name}\".`,\n extension\n );\n return admitted;\n };\n };\n layer.rules[model] = read;\n }\n}\n\n/**\n * The entry is read the first time a call needs its model, a filter that\n * reads the model through a relation included; its refusals fail that call.\n * Written apart from a rule, its entry is held, as `check`'s operand is.\n */\nexport function lazy<E>(\n read: () => HeldOperand<E>\n): IsHeld<E> extends true ? LazyWord<never> : LazyWord<E>;\nexport function lazy(read: () => unknown): unknown {\n return new Lazy(read);\n}\n"],"mappings":"ozBAiCA,MAAa,EAAa,OAAO,OAAO,EAAE,CAAC,CAG9B,MAAS,GACpB,IAAU,IAAA,GAOZ,SAAgB,aACd,EACA,EACS,CACT,GAAM,CAAE,SAAS,EAAK,OAAQ,EAAU,GAAQ,EAGhD,OAFI,EAAU,OAAS,SAAiB,CAAC,EAAQ,CAC7C,EAAU,OAAO,SAAW,EAAU,CAAC,EAAO,CAC3C,CACL,GAAG,IAAI,IAAI,CACT,GAAG,EAAU,OAAO,IAAK,GAAU,EAAM,QAAQ,IAAI,EAAM,EAAI,EAAO,CACtE,GAAI,EAAU,MAAQ,CAAC,EAAQ,CAAG,EAAE,CACrC,CAAC,CACH,CAMH,IAAM,YAAN,cAA0B,CAAa,CACrC,mBAA4B,EAAkB,EAA0B,CAEtE,OACE,MAAM,mBAAmB,EAAS,EAAM,EACxC,KAAK,KAAK,OAAO,IAAI,EAAM,KAAK,MAAM,GAAI,GAAK,IA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SAAgB,KAAK,EAA8B,CACjD,OAAO,IAAI,KAAK,EAAK"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{t,y as n}from"./base-z-cH5ZBI.mjs";import{p as r,t as i}from"./validation--qS7OPmg.mjs";import{t as a}from"./routed-operations-wytpbYKv.mjs";import{i as o,o as s}from"./value-guards-CBuxSC66.mjs";import{r as c}from"./extension-CGepsF-p.mjs";import{et as l}from"./native-types-DgjMUikz.mjs";import{i as u}from"./schema-BYA-_bpk.mjs";import{t as d}from"./raw-Dyq6Y6UX.mjs";function bindArguments(e,t,n,r){let i={...r};for(let[r,a]of Object.entries(n)){let n=e.find(e=>e.name===r&&e.extension===t&&e.bound===!0);n===void 0&&notBound(t,r),i[r]=n.admit(n,a)}return i}function notBound(e,t){return c(`Extension "${e}" binds argument "${t}", which it does not declare with bound(schema).`,e)}function argsOwnedBy(e,t){let n={};for(let r of t)e&&Object.hasOwn(e,r)&&(n[r]=e[r]);return n}const closedValues=e=>(t,n,r,i)=>{if(e.some(e=>e===n))return n;throw invalidArgument(t,r,i,[`must be one of ${e.map(e=>JSON.stringify(e)).join(`, `)}`])},checkedBy=e=>(n,r,i,a)=>{let o;try{o=e[`~standard`].validate(r)}catch(e){throw e instanceof t?e:validatorFailure(n,i,a,`threw`,e)}if(`then`in o)throw l(o),validatorFailure(n,i,a,`returned a promise`,TypeError(`Argument validators must return synchronously`));if(o.issues)throw invalidArgument(n,i,a,o.issues.map(e=>e.message));return o.value};function invalidArgument(e,t,n,r){return new i(n===void 0?{kind:`schema-builder`,builder:`$bind`,path:e.name}:{kind:`operation`,operation:n,model:t},r.map(t=>({path:e.name,message:`Argument "${e.name}" ${t}`})),{meta:{model:t,extension:e.extension}})}function validatorFailure(e,t,i,a,o){return new r(`Extension "${e.extension}" argument "${e.name}" validator for ${i===void 0?`$bind`:`${t}.${i}`} ${a}.`,{cause:n(o),meta:{model:t,operation:i}})}function appendArguments(e,t){let n=[...e?.all??[],...t],r=n.find(e=>e.bind)?.bind,i=new Set;for(let{name:e,extension:t}of n)i.has(e)&&c(`Extension "${t}" declares argument "${e}", which extension "${n.find(t=>t.name===e)?.extension}" already declares.`,t),i.add(e);let a=new Map,placed=(e,t)=>u(a,`${e}\u0000${t}`,()=>n.filter(({on:n,models:r})=>(n===void 0||n.includes(t))&&(r===void 0||r.includes(e))));return{names:i,all:n,placed,owned:argsOwnedBy,admit:(e,t,n,r,i)=>{let a=placed(e,t);if(a.length===0)return;if(typeof r!=`object`||!r)return{args:r,values:void 0};let o,s;for(let t of a){let{name:a,required:c}=t,l;t.bound!==!0&&Object.hasOwn(r,a)&&(l=r[a],s??={...r},delete s[a]);let u=l===void 0?i?.[a]??t.default:t.admit(t,l,e,n);if(u!==void 0)(o??={})[a]=u;else if(c===!0||c?.includes(e))throw invalidArgument(t,e,n,[`is required`])}return{args:s??r,values:o}},bind:r&&((...e)=>r(n,...e))}}const f=Object.freeze(Object.create(null)),p=Object.freeze({client:()=>f,model:()=>f,force:()=>void 0}),m=new Set([`$driver`,`$schema`,`$transaction`,`$connect`,`$disconnect`,`$extends`]);function addMethods(e,t,n,r,i,a=``){let s=Object.assign(Object.create(null),e);for(let[e,c]of t){let t=`${i} method "${a}${e}"`;o(c)||n(`${t} must be a function`),(Object.hasOwn(s,e)||r(e))&&n(`${t} collides with the existing ${i} surface`),s[e]=c}return Object.freeze(s)}const clientLayer=({prior:t,answer:n,refuse:r})=>{let i,a=e(()=>i??=addMethods(t.client(),Object.entries(n()),r,e=>m.has(e)||Object.hasOwn(d,e),`client`),`methods`);return{client:a,model:t.model,force:()=>{t.force(),a()}}},modelLayer=({prior:t,answer:n,scope:r,refuse:i})=>{let c=new Map,l=e(e=>{let l=c.get(e);if(l===void 0){let u=n()[e],d=Reflect.get(r(),e),f=o(u)?Reflect.apply(u,void 0,[d,r()]):u;f!==void 0&&!s(f)&&i(`methods.${e} must be an object of methods`),l=addMethods(t.model(e),Object.entries(f??{}).map(([e,t])=>[e,o(t)?(...e)=>Reflect.apply(t,d,e):t]),i,e=>e===`then`||e===`$rows`||a.has(e),`model`,`${e}.`),c.set(e,l)}return l},`methods`);return{client:t.client,model:l,force:()=>{t.force();for(let e of Object.keys(n()))l(e)}}};function methodsPart(e,t,n){return{join({next:r,name:i,schema:a}){let o=r.methods;r.methods={bind:r=>{let l=o?.bind(r)??p,refuse=e=>c(`Extension "${i}" ${e}.`,i),u,scopeOf=()=>u??=r(l,i),d;return t({prior:l,answer:()=>{if(d!==void 0)return d;let t=Reflect.apply(e,void 0,[scopeOf()]);s(t)||refuse(`methods factory must return an object`);for(let e of Object.keys(t)){let t=n(e,a);t&&refuse(`methods returned "${e}", ${t}`)}return d=t,t},scope:scopeOf,refuse})},bindNone:(e,t,n)=>{for(let n of Object.keys(t))notBound(e,n);return{...n}}}}}}function methods(e){return methodsPart(e,clientLayer,e=>e.startsWith(`$`)?void 0:`which is not a $ client method (a model's are written with modelMethods)`)}function modelMethods(e){return methodsPart(e,modelLayer,(e,t)=>Object.hasOwn(t,e)?void 0:`which is not a model`)}export{checkedBy as a,bindArguments as i,modelMethods as n,closedValues as o,appendArguments as r,methods as t};
2
- //# sourceMappingURL=methods-part-ZY0f2AV_.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"methods-part-ZY0f2AV_.mjs","names":["methods"],"sources":["../src/extensions/arguments.ts","../src/extensions/methods.ts","../src/extensions/methods-part.ts"],"sourcesContent":["/**\n * Arguments: what `args` declares, placed on a chain and admitted once per\n * call. Brought by `args` alone: an extension that declares no argument\n * carries none of it.\n */\n\nimport { QueryError, ValidationError, VibORMError } from \"@errors\";\nimport { memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { Operation } from \"@query-engine/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { discardAsyncValidationResult } from \"@validation/parse-failure\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { extensionError } from \"./chain\";\nimport type { ResolvedArgs } from \"./chain-state\";\n\ntype ArgLiteral = string | number | boolean;\n\n/**\n * One argument an extension declares. Its values are a closed list or a\n * Standard Schema, and `admit` is the code that checks one, brought by the\n * word that declared it (`oneOf`, or `accepts` and `bound`), so a chain of\n * closed arguments carries no Standard Schema admission. `on` names the\n * operations that accept it (every operation when absent), `models` the\n * models (every model when absent). With `required`, a call on one of those\n * operations that does not pass it is refused: on every model that accepts\n * it, or on the models it lists. With `bound`, it is accepted only from a\n * binding (the client scope's `$bind`, which `bind` runs), never from a\n * call's arguments, so a call that passes it is refused as passing an\n * unknown key. With `volatile`, a call that holds a value of it has no key\n * (`key(run)`): a read that holds one is never served from a store nor kept\n * in one.\n */\nexport interface ArgDeclaration {\n /** A closed argument's values; absent for a Standard Schema's. */\n readonly oneOf?: readonly ArgLiteral[];\n readonly admit: AdmitValue;\n readonly on?: readonly string[];\n readonly models?: readonly string[];\n readonly required?: true | readonly string[];\n /** The value a call that passes none reads. */\n readonly default?: ArgLiteral;\n readonly bound?: boolean;\n readonly bind?: typeof bindArguments;\n readonly volatile?: boolean;\n}\n\n/** One value admitted for a call's (model, operation), or, without them, a binding. */\ntype AdmitValue = (\n argument: ResolvedArg,\n value: unknown,\n model?: string,\n operation?: Operation\n) => unknown;\n\n/**\n * One argument of a chain: its declaration as written, its name and the\n * extension that declares it. Its declaration alone places it: no other part\n * moves it.\n */\nexport type ResolvedArg = ArgDeclaration & {\n readonly name: string;\n readonly extension: string;\n};\n\n/** The arguments one call admitted, by name; one it did not pass is absent. */\nexport type AdmittedArgs = Readonly<Record<string, unknown>>;\n\nexport interface ArgAdmission {\n /** The call's arguments without the chain's; the input itself when it passed none. */\n readonly args: Record<string, unknown>;\n /** `undefined` when the call admitted no value. */\n readonly values: AdmittedArgs | undefined;\n}\n\n/**\n * The values a view binds after one extension binds its own arguments: each\n * admitted once, over the values the view already binds, a value replacing\n * an earlier one. Brought by `bound`: only a `bound` argument is bound.\n */\nexport function bindArguments(\n all: readonly ResolvedArg[],\n extension: string,\n values: Readonly<Record<string, unknown>>,\n previous: AdmittedArgs | undefined\n): AdmittedArgs {\n const next: Record<string, unknown> = { ...previous };\n for (const [name, raw] of Object.entries(values)) {\n const argument = all.find(\n (candidate) =>\n candidate.name === name &&\n candidate.extension === extension &&\n candidate.bound === true\n );\n if (argument === undefined) notBound(extension, name);\n next[name] = argument.admit(argument, raw);\n }\n return next;\n}\n\n/** The refusal of a `$bind` naming an argument its extension does not declare `bound`. */\nexport function notBound(extension: string, name: string): never {\n return extensionError(\n `Extension \"${extension}\" binds argument \"${name}\", which it does not declare with bound(schema).`,\n extension\n );\n}\n\n/** One extension's own admitted arguments, as its parts see them (`c.values`). */\nfunction argsOwnedBy(\n admitted: AdmittedArgs | undefined,\n names: readonly string[]\n): AdmittedArgs {\n const owned: Record<string, unknown> = {};\n for (const name of names)\n if (admitted && Object.hasOwn(admitted, name)) owned[name] = admitted[name];\n return owned;\n}\n\n/** What admits a value of one of `values`, brought by `oneOf`. */\nexport const closedValues =\n (values: readonly ArgLiteral[]): AdmitValue =>\n (argument, value, model, operation) => {\n if (values.some((allowed) => allowed === value)) return value;\n throw invalidArgument(argument, model, operation, [\n `must be one of ${values.map((allowed) => JSON.stringify(allowed)).join(\", \")}`,\n ]);\n };\n\n/** What admits a value `schema` checks, brought by `accepts` and `bound`. */\nexport const checkedBy =\n (schema: StandardSchemaV1): AdmitValue =>\n (argument, value, model, operation) => {\n let result: ReturnType<StandardSchemaV1[\"~standard\"][\"validate\"]>;\n try {\n result = schema[\"~standard\"].validate(value);\n } catch (cause) {\n // A validator may own its typed failure; anything else is a failure of\n // extension code, as a throwing first moment is.\n if (cause instanceof VibORMError) throw cause;\n throw validatorFailure(argument, model, operation, \"threw\", cause);\n }\n if (\"then\" in result) {\n // The refused promise is still live; without a handler its rejection\n // would surface as an unhandled rejection (D-37).\n discardAsyncValidationResult(result);\n throw validatorFailure(\n argument,\n model,\n operation,\n \"returned a promise\",\n new TypeError(\"Argument validators must return synchronously\")\n );\n }\n if (result.issues)\n throw invalidArgument(\n argument,\n model,\n operation,\n result.issues.map((issue) => issue.message)\n );\n return result.value;\n };\n\nfunction invalidArgument(\n argument: ResolvedArg,\n model: string | undefined,\n operation: Operation | undefined,\n messages: readonly string[]\n): ValidationError {\n return new ValidationError(\n operation === undefined\n ? { kind: \"schema-builder\", builder: \"$bind\", path: argument.name }\n : { kind: \"operation\", operation, model },\n messages.map((message) => ({\n path: argument.name,\n message: `Argument \"${argument.name}\" ${message}`,\n })),\n { meta: { model, extension: argument.extension } }\n );\n}\n\nfunction validatorFailure(\n argument: ResolvedArg,\n model: string | undefined,\n operation: Operation | undefined,\n failure: string,\n cause: unknown\n): QueryError {\n return new QueryError(\n `Extension \"${argument.extension}\" argument \"${argument.name}\" validator for ${operation === undefined ? \"$bind\" : `${model}.${operation}`} ${failure}.`,\n { cause: errorCause(cause), meta: { model, operation } }\n );\n}\n\n/**\n * The chain's arguments with one extension's added, each (model, operation)\n * listing the ones it accepts the first time a call asks. One name, one\n * argument: a call's value is read once and admitted against one\n * declaration, so a second declaration of a name would refuse every call\n * that passes either value, and a binding would answer for both.\n */\nexport function appendArguments(\n previous: ResolvedArgs | undefined,\n declared: readonly ResolvedArg[]\n): ResolvedArgs {\n const all = [...(previous?.all ?? []), ...declared];\n const binder = all.find((argument) => argument.bind)?.bind;\n const names = new Set<string>();\n for (const { name, extension } of all) {\n if (names.has(name))\n extensionError(\n `Extension \"${extension}\" declares argument \"${name}\", which extension \"${all.find((argument) => argument.name === name)?.extension}\" already declares.`,\n extension\n );\n names.add(name);\n }\n const lists = new Map<string, readonly ResolvedArg[]>();\n const placed = (model: string, operation: string): readonly ResolvedArg[] => {\n const key = `${model}\\u0000${operation}`;\n return memo(lists, key, () =>\n all.filter(\n ({ on, models }) =>\n (on === undefined || on.includes(operation)) &&\n (models === undefined || models.includes(model))\n )\n );\n };\n return {\n names,\n all,\n placed,\n owned: argsOwnedBy,\n /**\n * Take every argument placed on this operation out of the call's\n * arguments and admit each once, before any first moment runs. A key\n * naming an argument placed elsewhere, or a bound one, stays in the\n * arguments, where core validation refuses it as an unknown key. An\n * argument the call did not pass takes the value its view binds, else\n * its default; without either it is refused where it is required.\n */\n admit: (\n model: string,\n placement: string,\n operation: Operation,\n input: Record<string, unknown>,\n bound: AdmittedArgs | undefined\n ): ArgAdmission | undefined => {\n const list = placed(model, placement);\n if (list.length === 0) return undefined;\n // Arguments that are not an object hold no extension argument: core\n // validation refuses them as it does on a client without extensions.\n if (typeof input !== \"object\" || input === null) {\n return { args: input, values: undefined };\n }\n let values: Record<string, unknown> | undefined;\n let args: Record<string, unknown> | undefined;\n for (const argument of list) {\n const { name, required } = argument;\n let raw: unknown;\n if (argument.bound !== true && Object.hasOwn(input, name)) {\n raw = input[name];\n args ??= { ...input };\n delete args[name];\n }\n // A bound value was admitted once, when its view was bound.\n const value =\n raw === undefined\n ? (bound?.[name] ?? argument.default)\n : argument.admit(argument, raw, model, operation);\n if (value !== undefined) (values ??= {})[name] = value;\n else if (required === true || required?.includes(model)) {\n throw invalidArgument(argument, model, operation, [\"is required\"]);\n }\n }\n return { args: args ?? input, values };\n },\n // Brought by `bound`: a chain that declares no bound argument binds none.\n bind: binder && ((...binding) => binder(all, ...binding)),\n };\n}\n","import type { TransactionClient, VibORMConfig } from \"@client/client\";\nimport {\n RAW_METHOD_NAMES,\n type RawSurface,\n type RowsFragment,\n} from \"@client/raw\";\nimport type { ClientSchema } from \"@client/schema-links\";\nimport type {\n Client,\n ClientRowsContext,\n ComputedOperation,\n ComputedOperations,\n Schema,\n StampedOperation,\n StampedOperations,\n} from \"@client/types\";\nimport type { ModelSql } from \"@query-engine/raptor3/shared/insert-value\";\nimport { ROUTED_OPERATIONS } from \"@query-engine/routed-operations\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { type AdmittedArgs, notBound } from \"./arguments\";\nimport type { ExtensionPart } from \"./chain\";\nimport { extensionError } from \"./chain\";\nimport type { NoArguments } from \"./contract\";\nimport type { MergeResultFields } from \"./result-types\";\n\ntype NoMethods = Record<never, never>;\ntype RuntimeExtensionMethodFunction = (...args: never[]) => unknown;\n\ndeclare const extensionResultConsumerState: unique symbol;\nexport interface ExtensionResultConsumerState {\n readonly [extensionResultConsumerState]: true;\n}\n\n/** The only static facts accumulated while extensions are chained. */\nexport interface ClientExtensionState<\n ClientMethods extends object = NoMethods,\n ModelMethods extends object = NoMethods,\n ResultConsumerState extends\n | ExtensionResultConsumerState\n | undefined = undefined,\n Arguments extends object = NoArguments,\n Filtered extends string = never,\n Defaults = never,\n Fields extends object = Record<never, never>,\n> {\n readonly client: ClientMethods;\n readonly models: ModelMethods;\n readonly resultConsumer: ResultConsumerState;\n /** The arguments the chain declares: each one's values and placement. */\n readonly args: Arguments;\n /** The models whose rows the chain's rules filter: a relation read can find none. */\n readonly filtered: Filtered;\n /** The fields the chain's `defaults` write on a create, which a caller no longer writes. */\n readonly defaults: Defaults;\n /** The fields the chain's `fields` compute, per model key, and their types. */\n readonly fields: Fields;\n}\n\nexport type EmptyClientExtensionState = ClientExtensionState;\n\n/** What every extension state is: the widest of each fact. */\nexport type ExtensionStateConstraint = ClientExtensionState<\n object,\n object,\n ExtensionResultConsumerState | undefined,\n object,\n string,\n unknown,\n object\n>;\n\n/** Whether an earlier extension was typed against result-bearing delegates. */\ntype HasResultConsumingExtension<X extends ExtensionStateConstraint> = [\n X[\"resultConsumer\"],\n] extends [undefined]\n ? false\n : [X[\"resultConsumer\"]] extends [ExtensionResultConsumerState]\n ? true\n : false;\n\ndeclare const delegateState: unique symbol;\n/**\n * Declaration-only: what a result read on a delegate of a chain that adds\n * model methods depends on (its client's config, the models the chain's\n * rules filter, its computed fields, the model), so a method typed with a\n * `this` parameter reads its result from the client it is called on\n * (`DelegateOperationResult`), whatever the chain added after it. Nothing\n * else of the extension state: a later step that changes none of these (the\n * cache) keeps the client assignable to the one before it. No property is\n * installed at runtime.\n */\nexport interface DelegateState<C, Rows, Result, ModelName> {\n readonly [delegateState]?: readonly [C, Rows, Result, ModelName];\n}\n\ntype MethodsForModel<\n X extends ExtensionStateConstraint,\n ModelName extends PropertyKey,\n> = ModelName extends keyof X[\"models\"] ? X[\"models\"][ModelName] : NoMethods;\n\n/**\n * The link, on every delegate of a chain that adds model methods: decided by\n * the extension state alone, so a client generic over its schema without\n * them (the empty state) compares as before.\n */\ntype DelegateLink<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n ModelName extends PropertyKey,\n> = [keyof X[\"models\"]] extends [never]\n ? unknown\n : DelegateState<C, X[\"filtered\"], X[\"fields\"], ModelName>;\n\n/**\n * One model's delegate after the chain's methods and arguments. On a chain\n * that writes `defaults` on a create, its writes may leave out the fields the chain\n * writes on a create.\n */\nexport type ExtensionModelDelegate<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n ModelName extends keyof ClientSchema<C>,\n> = ([X[\"defaults\"]] extends [never]\n ? Client<C, ClientRowsContext<C, X[\"filtered\"]>, X[\"args\"]>[ModelName]\n : Omit<\n Client<C, ClientRowsContext<C, X[\"filtered\"]>, X[\"args\"]>[ModelName],\n StampedOperation\n > &\n StampedOperations<\n C,\n ClientRowsContext<C, X[\"filtered\"]>,\n X[\"args\"],\n X[\"defaults\"],\n ModelName\n >) &\n MethodsForModel<X, ModelName> &\n DelegateLink<C, X, ModelName> &\n ModelRows;\n\n/** The core member every model delegate has beside its operations. */\ninterface ModelRows {\n /**\n * The rows of this model this client may read, as a `FROM` item of a\n * tagged `$queryRaw` named `alias`: a derived table filtered by the row\n * domain a `findMany` of this model on this client takes (permissions,\n * soft delete, bound arguments). Refused anywhere else.\n *\n * @example\n * ```ts\n * await db.$as(actor).$queryRaw`\n * SELECT p.id FROM ${db.$as(actor).page.$rows(\"p\")} WHERE p.title LIKE ${q}\n * `;\n * ```\n */\n $rows(alias: string): RowsFragment;\n /**\n * This model's names and values as this client's statements spell them:\n * its table, its columns, a value bound as one of its fields, and the rows\n * a call may see as a condition. For a fragment you write by hand and hand\n * to a model operation (a `computed` value, a filter's expression).\n */\n readonly $sql: ModelSql;\n}\n\n/**\n * One model's delegate on a chain that declares `fields`: its projecting\n * operations rebuilt so `select` and `omit` name the computed fields and the\n * rows carry them. A chain without `fields` never reaches this type.\n */\ntype ComputedModelDelegate<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n ModelName extends keyof ClientSchema<C>,\n> = Omit<ExtensionModelDelegate<C, X, ModelName>, ComputedOperation> &\n ComputedOperations<\n C,\n ClientRowsContext<C, X[\"filtered\"]>,\n X[\"args\"],\n X[\"defaults\"],\n ModelName,\n X[\"fields\"]\n >;\n\n/**\n * Model delegates after the methods contributed by the current chain. The\n * always-true test is deliberate: for a client generic over its config it\n * stays deferred, so the model map adds no index signature to that client and\n * its `$` members stay reachable inside a body generic over `C`. A chain\n * that declares `fields` is told apart here, once per client.\n */\nexport type ExtensionModelClient<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = [keyof C[\"schema\"]] extends [PropertyKey]\n ? [keyof X[\"fields\"]] extends [never]\n ? {\n [ModelName in keyof ClientSchema<C>]: ExtensionModelDelegate<\n C,\n X,\n ModelName\n >;\n }\n : {\n [ModelName in keyof ClientSchema<C>]: ComputedModelDelegate<\n C,\n X,\n ModelName\n >;\n }\n : unknown;\n\n/** The surface given to one client-method factory. */\nexport type ExtensionClientScope<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = ExtensionModelClient<C, X> &\n RawSurface &\n X[\"client\"] & {\n readonly $schema: ClientSchema<C>;\n readonly $transaction: TransactionClient<C, X>[\"$transaction\"];\n /**\n * The client this scope's methods are called on, its calls admitting\n * these values of this extension's own arguments as if passed (a\n * `bound: true` argument only from here). Its type is that client's,\n * which only the method knows: declare it with a `this` parameter,\n * `$with<Self>(this: Self, value: Value): Self`, outside the returned\n * literal (inside it, the factory's contextual type makes `Self` void).\n */\n readonly $bind: (values: Readonly<Record<string, unknown>>) => unknown;\n };\n\nexport type MergeModelMethods<Left extends object, Right extends object> = {\n readonly [ModelName in\n | keyof Left\n | keyof Right]: (ModelName extends keyof Left\n ? Left[ModelName]\n : NoMethods) &\n (ModelName extends keyof Right ? Right[ModelName] : NoMethods);\n};\n\n/** Incoming facts keep their nominal bit derivation inside this named state. */\nexport interface AddedExtensionState<\n ClientMethods extends object,\n ModelMethods extends object,\n Arguments extends object,\n Filtered extends string,\n Defaults,\n ConsumerContext extends string,\n // Defaulted: 1.3.3 exported this state with six parameters.\n Fields extends object = Record<never, never>,\n> extends ExtensionStateConstraint {\n readonly client: ClientMethods;\n readonly models: ModelMethods;\n readonly resultConsumer: ConsumerContext extends \"result-consuming\"\n ? ExtensionResultConsumerState\n : undefined;\n readonly args: Arguments;\n readonly filtered: Filtered;\n readonly defaults: Defaults;\n readonly fields: Fields;\n}\n\n/** Accumulate the same seven facts lazily, without retaining callback definitions. */\nexport interface ChainedExtensionState<\n X extends ExtensionStateConstraint,\n Added extends ExtensionStateConstraint,\n> extends ExtensionStateConstraint {\n readonly client: X[\"client\"] & Added[\"client\"];\n readonly models: MergeModelMethods<X[\"models\"], Added[\"models\"]>;\n readonly resultConsumer: HasResultConsumingExtension<Added> extends true\n ? ExtensionResultConsumerState\n : X[\"resultConsumer\"];\n readonly args: X[\"args\"] & Added[\"args\"];\n readonly filtered: X[\"filtered\"] | Added[\"filtered\"];\n readonly defaults: X[\"defaults\"] | Added[\"defaults\"];\n readonly fields: MergeResultFields<X[\"fields\"], Added[\"fields\"]>;\n}\n\ntype MethodRecord = Readonly<Record<string, RuntimeExtensionMethodFunction>>;\n\n/**\n * The methods a view answers after some prefix of its chain: its client\n * methods, and one model's. Each is computed the first time it is read.\n */\nexport interface ExtensionMethods {\n readonly client: () => MethodRecord;\n readonly model: (model: string) => MethodRecord;\n}\n\n/** A view's methods, and what invokes every factory of its chain in order. */\ntype BoundExtensionMethods = ExtensionMethods & {\n readonly force: () => void;\n};\n\nconst NO_METHODS: MethodRecord = /* @__PURE__ */ Object.freeze(\n Object.create(null)\n);\nconst NO_LAYER: BoundExtensionMethods = /* @__PURE__ */ Object.freeze({\n client: () => NO_METHODS,\n model: () => NO_METHODS,\n force: () => undefined,\n});\n\nconst CORE_CLIENT_METHODS = new Set([\n \"$driver\",\n \"$schema\",\n \"$transaction\",\n \"$connect\",\n \"$disconnect\",\n \"$extends\",\n]);\n\n/**\n * The methods before one extension with its own added, each a function and\n * each name (`at` the model's, for a model method) checked against what the\n * view already answers.\n */\nfunction addMethods(\n previous: MethodRecord,\n added: readonly (readonly [string, unknown])[],\n refuse: (problem: string) => never,\n collides: (name: string) => boolean,\n surface: \"client\" | \"model\",\n at = \"\"\n): MethodRecord {\n const methods: Record<string, RuntimeExtensionMethodFunction> = Object.assign(\n Object.create(null),\n previous\n );\n for (const [name, method] of added) {\n const label = `${surface} method \"${at}${name}\"`;\n if (!isFunction(method)) refuse(`${label} must be a function`);\n if (Object.hasOwn(methods, name) || collides(name))\n refuse(`${label} collides with the existing ${surface} surface`);\n methods[name] = method;\n }\n return Object.freeze(methods);\n}\n\n/**\n * What one factory's methods add to a view, given the view's methods before\n * it: brought by the builder (`methods` its client methods, `modelMethods`\n * its model methods), so an extension carries only the half it writes. Its\n * `force` forces the view before it first.\n */\ntype MethodsLayer = (made: {\n readonly prior: BoundExtensionMethods;\n /** The factory's answer, once per view, each key checked by `owns`. */\n readonly answer: () => Readonly<Record<string, unknown>>;\n readonly scope: () => object;\n readonly refuse: (problem: string) => never;\n}) => BoundExtensionMethods;\n\n/** `methods`' half: the `$` client methods its factory returns. */\nexport const clientLayer: MethodsLayer = ({ prior, answer, refuse }) => {\n let client: MethodRecord | undefined;\n const methods = () =>\n (client ??= addMethods(\n prior.client(),\n Object.entries(answer()),\n refuse,\n (method) =>\n CORE_CLIENT_METHODS.has(method) ||\n Object.hasOwn(RAW_METHOD_NAMES, method),\n \"client\"\n ));\n return {\n client: methods,\n model: prior.model,\n force: () => {\n prior.force();\n methods();\n },\n };\n};\n\n/**\n * `modelMethods`' half: each model's methods, made the first time the model\n * is read on a view; a model's entry may be a function of its delegate and\n * the scope, and a model method is called with `this` equal to its delegate.\n */\nexport const modelLayer: MethodsLayer = ({ prior, answer, scope, refuse }) => {\n const models = new Map<string, MethodRecord>();\n const methods = (model: string) => {\n let made = models.get(model);\n if (made === undefined) {\n const given = answer()[model];\n const delegate: unknown = Reflect.get(scope(), model);\n const own: unknown = isFunction(given)\n ? Reflect.apply(given, undefined, [delegate, scope()])\n : given;\n if (own !== undefined && !isRecord(own))\n refuse(`methods.${model} must be an object of methods`);\n made = addMethods(\n prior.model(model),\n Object.entries(own ?? {}).map(([method, fn]) => [\n method,\n isFunction(fn)\n ? (...args: unknown[]) => Reflect.apply(fn, delegate, args)\n : fn,\n ]),\n refuse,\n (method) =>\n method === \"then\" ||\n method === \"$rows\" ||\n ROUTED_OPERATIONS.has(method),\n \"model\",\n `${model}.`\n );\n models.set(model, made);\n }\n return made;\n };\n return {\n client: prior.client,\n model: methods,\n force: () => {\n prior.force();\n for (const key of Object.keys(answer())) methods(key);\n },\n };\n};\n\n/** A `methods` factory as its part keeps it. */\ntype RuntimeMethodsFactory = (scope: never) => unknown;\n\n/** A chain's methods, and what binds one view's methods. */\nexport interface ExtensionMethodsState {\n readonly bind: (\n createScope: (prior: ExtensionMethods, extension: string) => object\n ) => BoundExtensionMethods;\n /**\n * A factory scope's `$bind` on a chain that declares no `bound` argument:\n * it binds nothing, and refuses any argument it is asked to.\n */\n readonly bindNone: (\n extension: string,\n values: Readonly<Record<string, unknown>>,\n previous: AdmittedArgs | undefined\n ) => AdmittedArgs;\n}\n\n/**\n * A methods part: what a view answers, in chain order. `owns` (which keys\n * the factory may return: why not, else `undefined`) and `layer` (what its\n * methods add to a view) are its builder's half (`methods-part.ts`).\n *\n * A view's methods are this part's layer over the view the chain's methods\n * before it bind. The factory is invoked against the scope `createScope`\n * builds over those, the first time a method it returns could be read: a\n * view costs the factories it uses. `force` invokes every factory in chain\n * order, where a root view surfaces an extension's faults.\n */\nexport function methodsPart(\n factory: RuntimeMethodsFactory,\n layer: MethodsLayer,\n owns: (key: string, schema: Schema) => string | undefined\n): ExtensionPart {\n return {\n join({ next, name, schema }) {\n const before = next.methods;\n next.methods = {\n bind: (createScope) => {\n const prior = before?.bind(createScope) ?? NO_LAYER;\n // Typed where it is declared, so a call to it ends the argument flow.\n const refuse: (problem: string) => never = (problem) =>\n extensionError(`Extension \"${name}\" ${problem}.`, name);\n let scope: object | undefined;\n const scopeOf = () => (scope ??= createScope(prior, name));\n let returned: Readonly<Record<string, unknown>> | undefined;\n return layer({\n prior,\n // The factory's answer, once per view: the methods come from it.\n answer: () => {\n if (returned !== undefined) return returned;\n const value: unknown = Reflect.apply(factory, undefined, [\n scopeOf(),\n ]);\n if (!isRecord(value))\n refuse(\"methods factory must return an object\");\n for (const key of Object.keys(value)) {\n const problem = owns(key, schema);\n if (problem) refuse(`methods returned \"${key}\", ${problem}`);\n }\n returned = value;\n return value;\n },\n scope: scopeOf,\n refuse,\n });\n },\n bindNone: (extension, values, previous) => {\n for (const key of Object.keys(values)) notBound(extension, key);\n return { ...previous };\n },\n };\n },\n };\n}\n","/**\n * `methods((scope) => ({ $name: fn }))`: functions added to the client, and\n * `modelMethods((scope) => ({ model: { name: fn } }))`: functions added to\n * the models. Each factory runs once per view it serves, the first time one\n * of its methods is read; a model method is called with `this` equal to the\n * delegate it is read from. Two builders, each bringing its own half of the\n * methods host (`methods.ts`): an extension that adds client methods only\n * carries no model-method code, and the reverse.\n */\nimport type {\n AnyTarget,\n ConsumesResults,\n MethodsCheck,\n MethodsFacts,\n MethodsScope,\n ModelName,\n Part,\n} from \"./contract\";\nimport { clientLayer, methodsPart, modelLayer } from \"./methods\";\n\n/** Functions added to the client of the extension's chain: `$` names. */\nexport function methods<\n T extends AnyTarget,\n F extends (\n scope: MethodsScope<T>\n ) => MethodsCheck<ReturnType<F>, T, \"client\"> = (\n scope: MethodsScope<T>\n ) => object,\n>(factory: F): Part<T, MethodsFacts<ReturnType<F>, ConsumesResults<F>, never>>;\nexport function methods(factory: (scope: never) => unknown): unknown {\n return methodsPart(factory, clientLayer, (key) =>\n key.startsWith(\"$\")\n ? undefined\n : \"which is not a $ client method (a model's are written with modelMethods)\"\n );\n}\n\n/** Functions added to the models of the extension's chain, by model. */\nexport function modelMethods<\n T extends AnyTarget,\n F extends (\n scope: MethodsScope<T>\n ) => MethodsCheck<ReturnType<F>, T, \"model\"> = (\n scope: MethodsScope<T>\n ) => object,\n>(\n factory: F\n): Part<T, MethodsFacts<ReturnType<F>, ConsumesResults<F>, ModelName<T>>>;\nexport function modelMethods(factory: (scope: never) => unknown): unknown {\n return methodsPart(factory, modelLayer, (key, schema) =>\n Object.hasOwn(schema, key) ? undefined : \"which is not a model\"\n );\n}\n"],"mappings":"maA+EA,SAAgB,cACd,EACA,EACA,EACA,EACc,CACd,IAAM,EAAgC,CAAE,GAAG,EAAU,CACrD,IAAK,GAAM,CAAC,EAAM,KAAQ,OAAO,QAAQ,EAAO,CAAE,CAChD,IAAM,EAAW,EAAI,KAClB,GACC,EAAU,OAAS,GACnB,EAAU,YAAc,GACxB,EAAU,QAAU,GACvB,CACG,IAAa,IAAA,IAAW,SAAS,EAAW,EAAK,CACrD,EAAK,GAAQ,EAAS,MAAM,EAAU,EAAI,CAE5C,OAAO,EAIT,SAAgB,SAAS,EAAmB,EAAqB,CAC/D,OAAO,EACL,cAAc,EAAU,oBAAoB,EAAK,kDACjD,EACD,CAIH,SAAS,YACP,EACA,EACc,CACd,IAAM,EAAiC,EAAE,CACzC,IAAK,IAAM,KAAQ,EACb,GAAY,OAAO,OAAO,EAAU,EAAK,GAAE,EAAM,GAAQ,EAAS,IACxE,OAAO,EAIT,MAAa,aACV,IACA,EAAU,EAAO,EAAO,IAAc,CACrC,GAAI,EAAO,KAAM,GAAY,IAAY,EAAM,CAAE,OAAO,EACxD,MAAM,gBAAgB,EAAU,EAAO,EAAW,CAChD,kBAAkB,EAAO,IAAK,GAAY,KAAK,UAAU,EAAQ,CAAC,CAAC,KAAK,KAAK,GAC9E,CAAC,EAIO,UACV,IAC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Ac,GACxC,EAAI,WAAW,IAAI,CACf,IAAA,GACA,2EACL,CAcH,SAAgB,aAAa,EAA6C,CACxE,OAAO,YAAY,EAAS,YAAa,EAAK,IAC5C,OAAO,OAAO,EAAQ,EAAI,CAAG,IAAA,GAAY,uBAC1C"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t}from"./validation--qS7OPmg.mjs";import{o as n}from"./sql-3o4DOKm9.mjs";import{t as r}from"./adapter-result-parser-3WP82Cm-.mjs";import{N as i,T as a}from"./native-types-DgjMUikz.mjs";import{a as o}from"./adapter-internals-DOqI8IlQ.mjs";import{a as s}from"./physical-CeE2nYmI.mjs";import{t as ee}from"./geo-area-codec-mHrM3b9A.mjs";import{n as c}from"./result-parsing-B0Y4KGDT.mjs";import{r as l}from"./datetime-physical-codec-Dj-APo9f.mjs";import{t as u}from"./identifiers-s00pGES8.mjs";import{C as d,D as f,E as te,N as p,O as m,S as h,T as g,_,a as v,b as y,c as b,d as x,f as S,g as C,h as w,i as T,j as E,l as D,m as O,n as k,o as A,r as j,s as M,t as N,u as ne,v as P,w as F,y as I}from"./standard-sql-qLcQyCtK.mjs";import{n as L}from"./batch-refs-C-gx7A4-.mjs";import{t as R}from"./adapter-namespace-DaRiTIIf.mjs";import{a as z,d as B,f as V,i as H,m as U,n as W,o as G,p as K,r as q,t as J,u as Y}from"./select-assembly-DVI7d3tf.mjs";const X=u("`"),Z=U(()=>`PRIMARY`),Q={quotient:(e,t)=>n`CAST((${e} - MOD(${e}, ${t})) / ${t} AS DECIMAL(65,0))`,remainder:(e,t)=>n`MOD(${e}, ${t})`},mysqlMaximumCoefficient=e=>n.raw(`9`.repeat(e)),re=n`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`,$=n`JSON_EXTRACT('x', '$')`,decimalCast=(e,t,r)=>n`CAST(${e} AS ${n.raw(`DECIMAL(${t},${r})`)})`,mysqlCoefficient=(e,t)=>{let{scale:r}=t;if(r===0)return e;let i=Y(r),a=n`TRUNCATE(${e}, 0)`;return n`(${a} * ${i} + ${decimalCast(n`(${decimalCast(n`(${e} - ${a})`,r+1,r)} * ${i})`,r,0)})`},mysqlLogical=(e,t)=>{let{scale:r}=t;if(r===0)return e;let i=Y(r),a=n`MOD(${e}, ${i})`;return n`((${e} - ${a}) / ${i} + ${decimalCast(a,r,0)} * ${B(r)})`},mysqlGuardedDecimalAssignment=(e,t,r,i)=>{let a=mysqlMaximumCoefficient(r.precision),o=mysqlLogical(t,r);return n`${e} = CASE WHEN ${re} THEN ${o} WHEN ${e} IS NULL THEN NULL WHEN ${i} THEN CASE WHEN ${t} BETWEEN -${a} AND ${a} THEN ${o} ELSE ${$} END ELSE ${$} END`},mysqlDecimalIncrement=(e,t,r)=>{let i=mysqlCoefficient(e,r),a=mysqlCoefficient(t,r),o=mysqlMaximumCoefficient(r.precision),s=n`CASE WHEN ${a} > 0 THEN ${i} <= ${o} - ${a} WHEN ${a} < 0 THEN ${i} >= -${o} - ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,n`(${i} + ${a})`,r,s)},mysqlDecimalDecrement=(e,t,r)=>{let i=mysqlCoefficient(e,r),a=mysqlCoefficient(t,r),o=mysqlMaximumCoefficient(r.precision),s=n`CASE WHEN ${a} > 0 THEN ${i} >= -${o} + ${a} WHEN ${a} < 0 THEN ${i} <= ${o} + ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,n`(${i} - ${a})`,r,s)},mysqlDecimalMultiply=(e,t,r)=>{let i=mysqlCoefficient(e,r),a=mysqlCoefficient(t,r),o=mysqlMaximumCoefficient(65);return mysqlGuardedDecimalAssignment(e,G(Q,n`(${i} * ${a})`,Y(r.scale)),r,n`CASE WHEN ${a} = 0 THEN TRUE ELSE ABS(${i}) <= ${Q.quotient(o,n`ABS(${a})`)} END`)},mysqlDecimalDivide=(e,t,r)=>{let i=mysqlCoefficient(t,r);return mysqlGuardedDecimalAssignment(e,G(Q,V(n`(${mysqlCoefficient(e,r)} * ${Y(r.scale)})`,i),n`ABS(${i})`),r,n.raw`TRUE`)},mysqlDecimalAverage=(e,t)=>mysqlLogical(G(Q,n`SUM(${mysqlCoefficient(e,t)})`,n`COUNT(${e})`),t),caseFold=e=>n`LOWER(${e})`,ie=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?$/,naiveDateTimeToIso=e=>{let t=ie.exec(e);if(!t)return;let n=t[3]?t[3].padEnd(4,`0`).slice(0,4):`.000`;return`${t[1]}T${t[2]}${n}Z`},inlineIntegerLiteral=e=>{let t=e.values.length===1?e.values[0]:void 0;return typeof t==`number`&&Number.isInteger(t)?n.raw(String(t)):e},mysqlJsonObject=e=>{if(e.length===0)return n.raw`JSON_OBJECT()`;let t=e.flatMap(([e,t])=>[n`${e}`,t]);return n`JSON_OBJECT(${n.join(t,`, `)})`},mysqlJsonListValue=e=>n`CAST(${p(e)} AS JSON)`;var MySQLAdapter=class{constructor(e){R(this,e,`mysql`),this.identifiers=S(X,this.namespace,!0),K(this,this.geoPoint),o(this,{batchRefs:this.#t,constraints:Z,...this.namespace!==void 0&&{pinnedTable:this.identifiers.table},select:this.#e.select})}raw=d();identifiers;literals={...f(),true:()=>n.raw`TRUE`,false:()=>n.raw`FALSE`,json:e=>n`${JSON.stringify(e)}`,dateTime:(e,t,r)=>n`${r||e.length===10?e:l(e)}`,decimal:(e,t)=>n`CAST(${i(e,t,`text`)} AS ${n.raw(a(`mysql`,t))})`,id:(e,t)=>n`${e}`};operators={...v(),containsText:(e,t)=>n`LOCATE(BINARY ${t}, BINARY ${e}) > 0`,startsWithText:(e,t)=>n`LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,endsWithText:(e,t)=>n`RIGHT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,insensitiveText:(e,t,n)=>this.operators[`${e}Text`](caseFold(t),caseFold(n)),startsWithPrefix:(e,t)=>n`(${e} LIKE ${`${E(t)}%`} ESCAPE '\\\\' AND LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t})`,exactTextEq:(e,t)=>n`(${e} = ${t} AND BINARY ${e} = ${t})`,exactTextIn:(e,t)=>n`(${e} IN ${t} AND BINARY ${e} IN ${t})`,..._(),...I(),...h(),...C(this.literals.true,this.literals.false),...x()};expressions={...T(),caseFold,caseSensitiveText:e=>n`BINARY ${e}`,concat:(...e)=>e.length===0?n.raw`''`:e.length===1?e[0]:n`CONCAT(${n.join(e,`, `)})`,greatest:(...e)=>n`GREATEST(${n.join(e,`, `)})`,least:(...e)=>n`LEAST(${n.join(e,`, `)})`,integerDivide:(e,t)=>n`TRUNCATE(${e} / ${t}, 0)`,decimalCast:(e,t)=>decimalCast(e,t.precision,t.scale),idCast:(e,t)=>t===`bytes`?n`UNHEX(${e})`:n`CAST(${e} AS CHAR)`,cast:j({text:`CHAR`,integer:`SIGNED`,bigint:`SIGNED`,boolean:`UNSIGNED`,numeric:`DECIMAL`}),blobToHex:e=>n`LOWER(HEX(${e}))`};aggregates={...k(),decimalAvg:(e,t)=>mysqlDecimalAverage(e,t),decimalSumOperandPrecision:b(65)};json={equals:(e,t)=>n`${e} = ${t}`,number:e=>e,boolean:e=>n`JSON_EXTRACT(CASE WHEN ${e} THEN 'true' ELSE 'false' END, '$')`,document:e=>e,object:mysqlJsonObject,array:e=>e.length===0?n.raw`JSON_ARRAY()`:n`JSON_ARRAY(${n.join(e,`, `)})`,emptyArray:()=>n.raw`JSON_ARRAY()`,agg:e=>n`COALESCE(JSON_ARRAYAGG(${e}), JSON_ARRAY())`,objectFromColumns:mysqlJsonObject,extract:(e,t)=>n`JSON_EXTRACT(${e}, ${N(t)})`,extractText:(e,t)=>n`JSON_UNQUOTE(JSON_EXTRACT(${e}, ${N(t)}))`,numberAtPath:(e,t)=>{let r=N(t);return n`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${r})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${r})) AS DOUBLE) END)`},stringAtPath:(e,t)=>{let r=N(t);return n`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${r})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${r})) AS BINARY) END)`},foldableStringAtPath:(e,t)=>{let r=N(t);return n`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${r})) = 'STRING' THEN JSON_UNQUOTE(JSON_EXTRACT(${e}, ${r})) END)`},contains:(e,t)=>n`JSON_CONTAINS(${e}, ${t})`,lastElement:e=>n`JSON_EXTRACT(${e}, '$[last]')`,value:e=>n`CAST(${p(e)} AS JSON)`};arrays={literal:e=>e.length===0?n.raw`JSON_ARRAY()`:n`JSON_ARRAY(${n.join(e,`, `)})`,value:mysqlJsonListValue,enumValue:mysqlJsonListValue,has:(e,t)=>n`JSON_CONTAINS(${e}, JSON_ARRAY(${t}))`,hasEvery:(e,t)=>n`JSON_CONTAINS(${e}, ${t})`,hasSome:(e,t)=>n`JSON_OVERLAPS(${e}, ${t})`,isEmpty:e=>n`(JSON_LENGTH(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>n`CAST(${e} AS CHAR)`,length:e=>n`JSON_LENGTH(${e})`,get:(e,t)=>n`JSON_EXTRACT(${e}, CONCAT('$[', ${t}, ']'))`,push:(e,t)=>n`JSON_ARRAY_APPEND(${e}, '$', ${t})`,set:(e,t,r)=>n`JSON_SET(${e}, CONCAT('$[', ${t}, ']'), ${r})`};orderBy={...D(),...ne()};clauses={...te(),limit:e=>n`LIMIT ${inlineIntegerLiteral(e)}`,offset:e=>n`OFFSET ${inlineIntegerLiteral(e)}`};set={...y(),increment:(e,t,r)=>r?.decimal?mysqlDecimalIncrement(e,t,r.decimal):n`${e} = ${e} + ${t}`,decrement:(e,t,r)=>r?.decimal?mysqlDecimalDecrement(e,t,r.decimal):n`${e} = ${e} - ${t}`,multiply:(e,t,r)=>r?.decimal?mysqlDecimalMultiply(e,t,r.decimal):n`${e} = ${e} * ${t}`,divide:(e,t,r)=>r?.decimal?mysqlDecimalDivide(e,t,r.decimal):r?.integer?n`${e} = TRUNCATE(${e} / ${t}, 0)`:n`${e} = ${e} / ${t}`,push:(e,t)=>n`${e} = JSON_MERGE_PRESERVE(COALESCE(${e}, JSON_ARRAY()), ${t})`,unshift:(e,t)=>n`${e} = JSON_MERGE_PRESERVE(${t}, COALESCE(${e}, JSON_ARRAY()))`};filters=F();subqueries=m(X);noLimitValue=n.raw`18446744073709551615`;#e={select:e=>{let t={...e,limit:e.limit&&inlineIntegerLiteral(e.limit),offset:e.offset&&inlineIntegerLiteral(e.offset)};return t.distinct?J(t,t.distinct,this.identifiers.escape,this.noLimitValue):W(n`SELECT ${t.columns}`,t,{forUpdate:`append`,noLimitValue:this.noLimitValue})}};cte=M(X);mutations={skipDuplicatesStrategy:`recoverableUniqueError`,insert:O(X),insertAbsent:(e,t,r,i,a,o)=>{let name=e=>n.raw(X(e));return r.flatMap(r=>[n`INSERT INTO ${e} (${n.join(t.map(name),`, `)}) SELECT * FROM (SELECT ${n.join(r.map((e,r)=>n`${e} AS ${name(t[r])}`),`, `)}) AS \`new\` WHERE NOT EXISTS (SELECT 1 FROM ${e} AS \`old\` WHERE ${n.join(i.map(e=>n`\`old\`.${name(e)} = \`new\`.${name(e)}`),` AND `)})`,...a?[n`UPDATE ${e} SET ${a} WHERE ${n.join(i.map(e=>n`${name(e)} = ${r[t.indexOf(e)]}`),` AND `)}${o?n` AND NOT (${o})`:n.empty}`]:[]])},insertDefault:e=>n`INSERT INTO ${e} () VALUES ()`,...P(),updateFrom:(e,t,r,i,a)=>n`UPDATE ${e} JOIN ${r} ON ${i} SET ${t}${a?n` WHERE ${a}`:n.empty}`,returning:e=>n.empty,onConflict:(e,t,r)=>n`ON DUPLICATE KEY UPDATE ${t}`,onConflictUpdate:(e,t)=>e,skipDuplicates:e=>{let t=n.raw(X(e));return{prefix:n.empty,suffix:n`ON DUPLICATE KEY UPDATE ${t} = ${t}`}}};assertions={exists:e=>n`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,notExists:e=>n`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``};joins={...A(),full:(e,t)=>{throw Error(`MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},...w(X)};setOperations=g();capabilities={supportsReturning:!1,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!1,supportsTargetedUpsert:!1,supportsMutationTargetInSubquery:!1,supportsMutationRowLimit:!0,supportsRowLocks:!0,locksMissingKeys:!0,boundsRecursionIterations:!0};lastInsertId=()=>n.raw`LAST_INSERT_ID()`;#t=L({table:n.raw`\`__viborm_batch_refs\``,batchIdColumn:n.raw`\`batch_id\``,keyColumn:n.raw`\`ref_key\``,valueColumn:n.raw`\`ref_value\``,duplicateValue:n.raw`VALUES(\`ref_value\`)`,createTable:n.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \`__viborm_batch_refs\` (\`batch_id\` VARCHAR(191) NOT NULL, \`ref_key\` VARCHAR(191) NOT NULL, \`ref_value\` TEXT, PRIMARY KEY (\`batch_id\`, \`ref_key\`))`,castValue:e=>n`CAST((${e}) AS CHAR)`,lastInsertId:()=>this.lastInsertId()});vector=t;geoPoint=(()=>{let longitude=e=>n`ST_Longitude(${e})`,latitude=e=>n`ST_Latitude(${e})`;return{value:(e,t)=>n`ST_GeomFromText(CONCAT('POINT(', ${e}, ' ', ${t}, ')'), 4326, 'axis-order=long-lat')`,longitude,latitude,...q(longitude,latitude,this.operators,(e,t)=>{let r=H(t);if(r.length!==0)return this.operators.or(...r.map(t=>n`MBRIntersects(${e}, ST_GeomFromGeoJSON(${t}, 1, 4326))`))}),withinPolygon:(e,t)=>n`ST_Intersects(${n`ST_GeomFromGeoJSON(${z(t)}, 1, 4326)`}, ${e})`,distance:(e,t)=>n`ST_Distance_Sphere(${e}, ${t}, ${ee})`}})();result={decimalListRepresentation:`coefficient`,idRepresentation:(e,t)=>s(e,t,`mysql`)?.representation??`text`,parseResult:r,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>{if(t===`boolean`){let t=c(e===`0`?0:e===`1`?1:e);if(t!==void 0)return n(t)}if(t===`datetime`&&typeof e==`string`){let t=naiveDateTimeToIso(e);if(t!==void 0)return n(t)}return n()}}};export{MySQLAdapter as t};
2
- //# sourceMappingURL=mysql-adapter-C69j1sKh.mjs.map