viborm 1.14.2 → 1.16.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 (483) hide show
  1. package/dist/adapter-namespace-DwFnfpED.mjs +2 -0
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +26 -10
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/args-7WgBFd_f.mjs +2 -0
  6. package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
  7. package/dist/array-literal-BOzj0E2u.mjs +2 -0
  8. package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
  9. package/dist/base-17NSFtrA.mjs +2 -0
  10. package/dist/base-17NSFtrA.mjs.map +1 -0
  11. package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
  12. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
  13. package/dist/better-auth.d.mts +116 -0
  14. package/dist/better-auth.mjs +6 -0
  15. package/dist/better-auth.mjs.map +1 -0
  16. package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
  17. package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
  18. package/dist/bun-sql.d.mts +1 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/bun-sqlite.mjs.map +1 -1
  24. package/dist/cache/cloudflare-kv.d.mts +1 -1
  25. package/dist/cache/cloudflare-kv.mjs +1 -1
  26. package/dist/cache/cloudflare-kv.mjs.map +1 -1
  27. package/dist/cache/memory.d.mts +1 -1
  28. package/dist/cache/memory.mjs +1 -1
  29. package/dist/cache/memory.mjs.map +1 -1
  30. package/dist/cache.d.mts +2 -2
  31. package/dist/cache.mjs +1 -1
  32. package/dist/cache.mjs.map +1 -1
  33. package/dist/call-0bd_B9Vp.mjs +2 -0
  34. package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
  35. package/dist/cli.mjs +6 -6
  36. package/dist/cli.mjs.map +1 -1
  37. package/dist/client-D7sWgUt2.mjs +2 -0
  38. package/dist/client-D7sWgUt2.mjs.map +1 -0
  39. package/dist/client-DEfFqv4S.mjs +9 -0
  40. package/dist/client-DEfFqv4S.mjs.map +1 -0
  41. package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
  42. package/dist/client.d.mts +3 -3
  43. package/dist/client.mjs +1 -1
  44. package/dist/client.mjs.map +1 -1
  45. package/dist/config.d.mts +2 -2
  46. package/dist/config.mjs +1 -1
  47. package/dist/confine-CyI9IwjC.mjs +2 -0
  48. package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
  49. package/dist/coordination-BxMskOgi.mjs +2 -0
  50. package/dist/coordination-BxMskOgi.mjs.map +1 -0
  51. package/dist/d1.d.mts +2 -30
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
  55. package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
  56. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
  57. package/dist/defaults-DAPb-tJ4.mjs +2 -0
  58. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
  59. package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
  60. package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
  61. package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
  62. package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
  63. package/dist/driver-kiIQS_Fd.mjs +2 -0
  64. package/dist/driver-kiIQS_Fd.mjs.map +1 -0
  65. package/dist/driver-lShUkDmf.mjs +2 -0
  66. package/dist/driver-lShUkDmf.mjs.map +1 -0
  67. package/dist/driver.d.mts +1 -1
  68. package/dist/driver.mjs +1 -1
  69. package/dist/durable-object.d.mts +1 -1
  70. package/dist/durable-object.mjs +2 -2
  71. package/dist/durable-object.mjs.map +1 -1
  72. package/dist/error-mapping-B9rSvgG9.mjs +2 -0
  73. package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
  74. package/dist/every-JpbiHdMb.mjs +2 -0
  75. package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
  76. package/dist/execution-context-couU2tgh.mjs +2 -0
  77. package/dist/execution-context-couU2tgh.mjs.map +1 -0
  78. package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
  79. package/dist/extension-Dh1ddrlA.mjs +2 -0
  80. package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
  81. package/dist/fs-estate-n-QpsFqb.mjs +2 -0
  82. package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
  83. package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
  84. package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
  85. package/dist/id-domain-Cg65TLZ-.mjs +2 -0
  86. package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
  87. package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
  88. package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
  89. package/dist/identifiers-BxOf57qy.mjs +2 -0
  90. package/dist/identifiers-BxOf57qy.mjs.map +1 -0
  91. package/dist/identity-CJlRQA-m.mjs +2 -0
  92. package/dist/identity-CJlRQA-m.mjs.map +1 -0
  93. package/dist/index.d.mts +3 -3
  94. package/dist/index.mjs +1 -1
  95. package/dist/index.mjs.map +1 -1
  96. package/dist/instrumentation.d.mts +1 -1
  97. package/dist/instrumentation.mjs +1 -1
  98. package/dist/instrumentation.mjs.map +1 -1
  99. package/dist/introspect-q3Rf_Xv8.mjs +2 -0
  100. package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
  101. package/dist/json-CsAdz9pg.mjs +2 -0
  102. package/dist/json-CsAdz9pg.mjs.map +1 -0
  103. package/dist/json-number-C09rsm1g.mjs +2 -0
  104. package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
  105. package/dist/json-parameter-D7hDrVKw.mjs +2 -0
  106. package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
  107. package/dist/judge-words-k5GCc4cV.mjs +2 -0
  108. package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
  109. package/dist/key-BDH6oTyC.mjs +2 -0
  110. package/dist/key-BDH6oTyC.mjs.map +1 -0
  111. package/dist/keys-CIal55WQ.mjs +2 -0
  112. package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
  113. package/dist/keys-DZdKAd4n.mjs +2 -0
  114. package/dist/keys-DZdKAd4n.mjs.map +1 -0
  115. package/dist/libsql-DEZ0uhK2.mjs +3 -0
  116. package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
  117. package/dist/libsql.d.mts +2 -20
  118. package/dist/libsql.mjs +1 -1
  119. package/dist/libsql.mjs.map +1 -1
  120. package/dist/light-D2wNSbzY.mjs +2 -0
  121. package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
  122. package/dist/memory-BaGWNdvk.mjs +2 -0
  123. package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
  124. package/dist/methods-part-BaNx3o7b.mjs +2 -0
  125. package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
  126. package/dist/migrations/mysql.d.mts +5 -5
  127. package/dist/migrations/mysql.mjs +1 -1
  128. package/dist/migrations/postgres.d.mts +5 -5
  129. package/dist/migrations/postgres.mjs +1 -1
  130. package/dist/migrations/snowflake.d.mts +5 -5
  131. package/dist/migrations/snowflake.mjs +1 -1
  132. package/dist/migrations/sqlite.d.mts +5 -5
  133. package/dist/migrations/sqlite.mjs +1 -1
  134. package/dist/migrations/storage/durable-object.d.mts +1 -1
  135. package/dist/migrations/storage/durable-object.mjs +1 -1
  136. package/dist/migrations/storage/durable-object.mjs.map +1 -1
  137. package/dist/migrations/storage/fs.d.mts +1 -1
  138. package/dist/migrations/storage/fs.mjs +1 -1
  139. package/dist/migrations/storage/r2.d.mts +1 -1
  140. package/dist/migrations/storage/r2.mjs +1 -1
  141. package/dist/migrations/storage/r2.mjs.map +1 -1
  142. package/dist/migrations/surrealdb.d.mts +5 -5
  143. package/dist/migrations/surrealdb.mjs +1 -1
  144. package/dist/migrations/tenant.d.mts +3 -3
  145. package/dist/migrations/tenant.mjs +1 -1
  146. package/dist/migrations/tenant.mjs.map +1 -1
  147. package/dist/migrations-DIUltjr3.mjs +2 -0
  148. package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
  149. package/dist/migrations.d.mts +5 -5
  150. package/dist/migrations.mjs +1 -1
  151. package/dist/model-Dtd37Sky.mjs +2 -0
  152. package/dist/model-Dtd37Sky.mjs.map +1 -0
  153. package/dist/mysql-BFPF8xyv.mjs +9 -0
  154. package/dist/mysql-BFPF8xyv.mjs.map +1 -0
  155. package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
  156. package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
  157. package/dist/mysql2.d.mts +2 -27
  158. package/dist/mysql2.mjs +1 -1
  159. package/dist/mysql2.mjs.map +1 -1
  160. package/dist/named-statements-CkOOD__I.mjs +2 -0
  161. package/dist/named-statements-CkOOD__I.mjs.map +1 -0
  162. package/dist/named-statements-NF7Iycjk.d.mts +13 -0
  163. package/dist/native-types-1ewJXVks.mjs +2 -0
  164. package/dist/native-types-1ewJXVks.mjs.map +1 -0
  165. package/dist/neon-http.d.mts +1 -1
  166. package/dist/neon-http.mjs +1 -1
  167. package/dist/neon-http.mjs.map +1 -1
  168. package/dist/normalized-result-D7nVkF36.mjs +2 -0
  169. package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
  170. package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
  171. package/dist/object-store-Chq1PMYz.mjs +2 -0
  172. package/dist/object-store-Chq1PMYz.mjs.map +1 -0
  173. package/dist/on-ZkOVmE4-.mjs +2 -0
  174. package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
  175. package/dist/on.d.mts +1 -1
  176. package/dist/on.mjs +1 -1
  177. package/dist/on.mjs.map +1 -1
  178. package/dist/ordering/keys.mjs +1 -1
  179. package/dist/ordering.d.mts +9 -3
  180. package/dist/ordering.mjs +10 -10
  181. package/dist/ordering.mjs.map +1 -1
  182. package/dist/pending-operation-D4gUKMxD.mjs +2 -0
  183. package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
  184. package/dist/permissions.d.mts +1 -1
  185. package/dist/permissions.mjs +1 -1
  186. package/dist/permissions.mjs.map +1 -1
  187. package/dist/pg.d.mts +16 -99
  188. package/dist/pg.mjs +1 -1
  189. package/dist/pg.mjs.map +1 -1
  190. package/dist/pglite.d.mts +3 -1
  191. package/dist/pglite.mjs +1 -1
  192. package/dist/pglite.mjs.map +1 -1
  193. package/dist/physical-DO4PEYcc.mjs +2 -0
  194. package/dist/physical-DO4PEYcc.mjs.map +1 -0
  195. package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
  196. package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
  197. package/dist/planetscale.d.mts +1 -1
  198. package/dist/planetscale.mjs +1 -1
  199. package/dist/planetscale.mjs.map +1 -1
  200. package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
  201. package/dist/postgres-DQQE2ys_.mjs +34 -0
  202. package/dist/postgres-DQQE2ys_.mjs.map +1 -0
  203. package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
  204. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
  205. package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
  206. package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
  207. package/dist/postgres-result-133boRW-.mjs +2 -0
  208. package/dist/postgres-result-133boRW-.mjs.map +1 -0
  209. package/dist/postgres.d.mts +27 -59
  210. package/dist/postgres.mjs +1 -1
  211. package/dist/postgres.mjs.map +1 -1
  212. package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
  213. package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
  214. package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
  215. package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
  216. package/dist/quantized-BKBs0joq.mjs +2 -0
  217. package/dist/quantized-BKBs0joq.mjs.map +1 -0
  218. package/dist/query-BTb6iakn.mjs +2 -0
  219. package/dist/query-BTb6iakn.mjs.map +1 -0
  220. package/dist/query-backend-TisPjCPF.mjs +2 -0
  221. package/dist/query-backend-TisPjCPF.mjs.map +1 -0
  222. package/dist/query-inspection-DwYBKSDG.mjs +2 -0
  223. package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
  224. package/dist/raw-DqEb71JZ.mjs +2 -0
  225. package/dist/raw-DqEb71JZ.mjs.map +1 -0
  226. package/dist/relation-bound-CSNKLyDy.mjs +2 -0
  227. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
  228. package/dist/result-parsing-BbffueEX.mjs +2 -0
  229. package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
  230. package/dist/routed-operations-CcKOdn51.mjs +2 -0
  231. package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
  232. package/dist/rows-of-Bgl9GVtK.mjs +2 -0
  233. package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
  234. package/dist/rule-words-DMbQuvD2.mjs +2 -0
  235. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
  236. package/dist/scalar-Dm9brvAU.mjs +4 -0
  237. package/dist/scalar-Dm9brvAU.mjs.map +1 -0
  238. package/dist/schema/introspect.d.mts +2 -2
  239. package/dist/schema/introspect.mjs +1 -1
  240. package/dist/schema/json.d.mts +6 -4
  241. package/dist/schema/json.mjs +1 -1
  242. package/dist/schema-DDkAUfOb.mjs +2 -0
  243. package/dist/schema-DDkAUfOb.mjs.map +1 -0
  244. package/dist/schema-DqR_Kcje.mjs +2 -0
  245. package/dist/schema-DqR_Kcje.mjs.map +1 -0
  246. package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
  247. package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
  248. package/dist/schema.d.mts +2 -2
  249. package/dist/schema.mjs +1 -1
  250. package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
  251. package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
  252. package/dist/serializer-ettLu5xG.mjs +33 -0
  253. package/dist/serializer-ettLu5xG.mjs.map +1 -0
  254. package/dist/settle-Pui-1tfJ.mjs +2 -0
  255. package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
  256. package/dist/settled-DYYPcaBX.mjs +2 -0
  257. package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
  258. package/dist/snowflake-BfF8xwfP.mjs +2 -0
  259. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
  260. package/dist/snowflake.d.mts +3 -3
  261. package/dist/snowflake.mjs +2 -2
  262. package/dist/snowflake.mjs.map +1 -1
  263. package/dist/soft-delete.d.mts +9 -3
  264. package/dist/soft-delete.mjs +1 -1
  265. package/dist/soft-delete.mjs.map +1 -1
  266. package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
  267. package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
  268. package/dist/sql-Bu63iAfT.mjs +2 -0
  269. package/dist/sql-Bu63iAfT.mjs.map +1 -0
  270. package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
  271. package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
  272. package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
  273. package/dist/sql-tegqTqGq.mjs +2 -0
  274. package/dist/sql-tegqTqGq.mjs.map +1 -0
  275. package/dist/sql.d.mts +1 -1
  276. package/dist/sql.mjs +1 -1
  277. package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
  278. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
  279. package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
  280. package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
  281. package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
  282. package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
  283. package/dist/sqlite3.d.mts +2 -46
  284. package/dist/sqlite3.mjs +1 -1
  285. package/dist/sqlite3.mjs.map +1 -1
  286. package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
  287. package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
  288. package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
  289. package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
  290. package/dist/surrealdb.d.mts +2 -2
  291. package/dist/surrealdb.mjs +1 -1
  292. package/dist/surrealdb.mjs.map +1 -1
  293. package/dist/surrealql-DY74AUeD.mjs +2 -0
  294. package/dist/surrealql-DY74AUeD.mjs.map +1 -0
  295. package/dist/time-step-DJaIhpAz.mjs +2 -0
  296. package/dist/time-step-DJaIhpAz.mjs.map +1 -0
  297. package/dist/transaction-Bv5nyp-U.mjs +2 -0
  298. package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
  299. package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
  300. package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
  301. package/dist/types-Dy33vBdd.mjs +2 -0
  302. package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
  303. package/dist/unit-DUPX5Sdd.mjs +2 -0
  304. package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
  305. package/dist/unit-words-BXpLpyr2.mjs +2 -0
  306. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
  307. package/dist/utils-BHkJsduV.mjs +26 -0
  308. package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
  309. package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
  310. package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
  311. package/dist/validation-ATmgN5RE.mjs +2 -0
  312. package/dist/validation-ATmgN5RE.mjs.map +1 -0
  313. package/dist/validation-BHjx13zG.mjs +2 -0
  314. package/dist/validation-BHjx13zG.mjs.map +1 -0
  315. package/dist/validation.d.mts +1 -1
  316. package/dist/validation.mjs +1 -1
  317. package/dist/validator-DMzH5Tz0.mjs +2 -0
  318. package/dist/validator-DMzH5Tz0.mjs.map +1 -0
  319. package/dist/value-guards-CBVIJXlI.mjs +2 -0
  320. package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
  321. package/dist/values-Ch2cTlss.mjs +2 -0
  322. package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
  323. package/dist/version-0BDwfy7C.mjs +2 -0
  324. package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
  325. package/dist/view-CHgjF2BO.mjs +2 -0
  326. package/dist/view-CHgjF2BO.mjs.map +1 -0
  327. package/dist/write-sinks-Bei5vFHP.mjs +2 -0
  328. package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
  329. package/package.json +50 -37
  330. package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
  331. package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
  332. package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
  333. package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
  334. package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
  335. package/dist/args-764KdWMr.mjs +0 -2
  336. package/dist/array-literal-DHinAnVs.mjs +0 -2
  337. package/dist/base-z-cH5ZBI.mjs +0 -2
  338. package/dist/base-z-cH5ZBI.mjs.map +0 -1
  339. package/dist/batch-refs-C-gx7A4-.mjs +0 -2
  340. package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
  341. package/dist/call-Cz8XUmrl.mjs +0 -2
  342. package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
  343. package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
  344. package/dist/chunk-BuuaeEvq.mjs +0 -1
  345. package/dist/client-DRpX3-vw.mjs +0 -2
  346. package/dist/client-DRpX3-vw.mjs.map +0 -1
  347. package/dist/client-y7TV0PRZ.mjs +0 -9
  348. package/dist/client-y7TV0PRZ.mjs.map +0 -1
  349. package/dist/confine-DqFBTUw6.mjs +0 -2
  350. package/dist/coordination-6qZHx_kl.mjs +0 -2
  351. package/dist/coordination-6qZHx_kl.mjs.map +0 -1
  352. package/dist/current-DBTlPsQg.mjs +0 -2
  353. package/dist/current-DBTlPsQg.mjs.map +0 -1
  354. package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
  355. package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
  356. package/dist/defaults-DwOHWI_M.mjs +0 -2
  357. package/dist/driver-BGVcgnIX.mjs +0 -2
  358. package/dist/driver-BGVcgnIX.mjs.map +0 -1
  359. package/dist/driver-BIXhOH2_.mjs +0 -2
  360. package/dist/driver-BIXhOH2_.mjs.map +0 -1
  361. package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
  362. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  363. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  364. package/dist/every-tOgQmaIE.mjs +0 -2
  365. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  366. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  367. package/dist/extension-CGepsF-p.mjs +0 -2
  368. package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
  369. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  370. package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
  371. package/dist/hydration-A3zffFWP.mjs +0 -2
  372. package/dist/hydration-A3zffFWP.mjs.map +0 -1
  373. package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
  374. package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
  375. package/dist/identifiers-s00pGES8.mjs +0 -2
  376. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  377. package/dist/identity-CtW15WlB.mjs +0 -2
  378. package/dist/identity-CtW15WlB.mjs.map +0 -1
  379. package/dist/introspect-Bm6xnXcG.mjs +0 -2
  380. package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
  381. package/dist/json-DgMc8-GU.mjs +0 -2
  382. package/dist/json-DgMc8-GU.mjs.map +0 -1
  383. package/dist/json-number-AI-SdUUn.mjs +0 -2
  384. package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
  385. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  386. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  387. package/dist/key-hxFFCKed.mjs +0 -2
  388. package/dist/key-hxFFCKed.mjs.map +0 -1
  389. package/dist/keys-BQxM4c_a.mjs +0 -2
  390. package/dist/libsql-DuGR904j.mjs +0 -3
  391. package/dist/libsql-DuGR904j.mjs.map +0 -1
  392. package/dist/light-BkJe3-yW.mjs +0 -2
  393. package/dist/memory-G4cSuc6A.mjs +0 -2
  394. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  395. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  396. package/dist/migrations-BMiRjR-N.mjs +0 -2
  397. package/dist/mysql-BNXWfTOo.mjs +0 -100
  398. package/dist/mysql-BNXWfTOo.mjs.map +0 -1
  399. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  400. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  401. package/dist/native-types-DgjMUikz.mjs +0 -2
  402. package/dist/native-types-DgjMUikz.mjs.map +0 -1
  403. package/dist/normalized-result-B8pifWS0.mjs +0 -2
  404. package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
  405. package/dist/object-store-DS0F0yZX.mjs +0 -2
  406. package/dist/object-store-DS0F0yZX.mjs.map +0 -1
  407. package/dist/on-ylYaKuRu.mjs +0 -2
  408. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  409. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  410. package/dist/physical-CeE2nYmI.mjs +0 -2
  411. package/dist/physical-CeE2nYmI.mjs.map +0 -1
  412. package/dist/pinned-session-DCoAZDOz.mjs +0 -2
  413. package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
  414. package/dist/postgres-CDdh5dSP.mjs +0 -437
  415. package/dist/postgres-CDdh5dSP.mjs.map +0 -1
  416. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  417. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  418. package/dist/postgres-adapter-axapXX8d.mjs +0 -2
  419. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  420. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  421. package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
  422. package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
  423. package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
  424. package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
  425. package/dist/query-BZVHfA0s.mjs +0 -2
  426. package/dist/query-BZVHfA0s.mjs.map +0 -1
  427. package/dist/query-inspection-BoG-yAln.mjs +0 -2
  428. package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
  429. package/dist/raw-Dyq6Y6UX.mjs +0 -2
  430. package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
  431. package/dist/relation-bound-ku_cMdye.mjs +0 -2
  432. package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
  433. package/dist/routed-operations-wytpbYKv.mjs +0 -2
  434. package/dist/rule-words-ZIGm7cDm.mjs +0 -2
  435. package/dist/scalar-BHCh7aUz.mjs +0 -4
  436. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  437. package/dist/schema-BYA-_bpk.mjs +0 -2
  438. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  439. package/dist/schema-CFIaebgi.mjs +0 -2
  440. package/dist/schema-CFIaebgi.mjs.map +0 -1
  441. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  442. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  443. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  444. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  445. package/dist/serializer-rBq3v1xr.mjs +0 -51
  446. package/dist/serializer-rBq3v1xr.mjs.map +0 -1
  447. package/dist/settle-1cy5x_52.mjs +0 -2
  448. package/dist/settled-BjyuA76m.mjs +0 -2
  449. package/dist/snowflake-UOCC820W.mjs +0 -2
  450. package/dist/sql-3o4DOKm9.mjs +0 -2
  451. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  452. package/dist/sql-Dl6nykFV.mjs +0 -2
  453. package/dist/sql-Dl6nykFV.mjs.map +0 -1
  454. package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
  455. package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
  456. package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
  457. package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
  458. package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
  459. package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
  460. package/dist/standard-sql-qLcQyCtK.mjs +0 -6
  461. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  462. package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
  463. package/dist/surrealql-C1dp1sWw.mjs +0 -2
  464. package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
  465. package/dist/to-many-BybuKQM1.mjs +0 -2
  466. package/dist/to-many-BybuKQM1.mjs.map +0 -1
  467. package/dist/transaction-BNomMtme.mjs +0 -2
  468. package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
  469. package/dist/types-DtDnXhwa.mjs +0 -2
  470. package/dist/unit-BhHbZyuJ.mjs +0 -2
  471. package/dist/unit-words-CT0yeqfZ.mjs +0 -2
  472. package/dist/utils-CpAojrCj.mjs +0 -26
  473. package/dist/validation--qS7OPmg.mjs +0 -2
  474. package/dist/validation--qS7OPmg.mjs.map +0 -1
  475. package/dist/validation-CYaJ8ndO.mjs +0 -2
  476. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  477. package/dist/validator-CZLW7aR3.mjs +0 -2
  478. package/dist/validator-CZLW7aR3.mjs.map +0 -1
  479. package/dist/value-guards-CBuxSC66.mjs +0 -2
  480. package/dist/values-B4aj1i1f.mjs +0 -2
  481. package/dist/version-CXGIA82S.mjs +0 -2
  482. package/dist/write-sinks-3IKCDF-S.mjs +0 -2
  483. /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"permissions.mjs","names":["type","memo","value","key","path","relation","models","bound","facts","rule","scope","target","row","left","right","known","summaries","names","written","P","walk","name","everyOperation","bound"],"sources":["../src/permissions/actor.ts","../src/permissions/rules.ts","../src/permissions/compile.ts","../src/permissions/index.ts"],"sourcesContent":["// The actor contract of viborm/permissions (plan §4.2 K2(e)): who calls is a\n// `viborm/validation` object schema, and every path a policy reads of it is one\n// of its entries. The schema is walked once, at `permissions()`, into the finite tree\n// of its paths; a path the tree does not hold is refused where the policy is\n// compiled, so a misspelt guard can never fold false at every call.\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { ClientInitializationError } from \"../errors\";\nimport type { VibSchema } from \"../validation\";\nimport { v } from \"../validation/primitives/v\";\n\n/** The paths below one actor value: named keys, or any key of a record. */\ninterface Paths {\n readonly keys?: ReadonlyMap<string, Paths>;\n readonly any?: Paths;\n readonly item?: Paths;\n}\n\n/** The members of a validation schema the walk reads. */\ninterface Walked {\n readonly type?: string;\n readonly entries?: Readonly<Record<string, unknown>>;\n readonly options?: NonNullable<Parameters<typeof v.object>[1]>;\n readonly wrapped?: unknown;\n readonly value?: unknown;\n readonly item?: unknown;\n}\n\n/** Schemas a path passes through without naming a key. */\nconst WRAPPERS = new Set([\"optional\", \"nullable\", \"lazyRef\"]);\n\nexport function refuse(\n message: string,\n model?: string,\n cause?: unknown\n): never {\n throw new ClientInitializationError(`viborm/permissions: ${message}`, {\n meta: { extension: \"viborm.permissions\", ...(model && { model }) },\n ...(cause !== undefined && {\n cause:\n cause instanceof Error\n ? cause\n : new Error(\"A non-Error value was thrown.\", { cause }),\n }),\n });\n}\n\n/** bindingSchema already resolved thunks and refused cycles. */\nfunction walk(input: unknown, at: string): Paths {\n let schema = input;\n for (;;) {\n // A viborm/validation schema, read for its kind and what it wraps.\n const { type, wrapped } = schema as Walked;\n if (type === undefined || !WRAPPERS.has(type)) break;\n schema = wrapped;\n }\n // The same schema, unwrapped, read for its children.\n const { type, entries, options, value, item } = schema as Walked;\n if (type !== \"object\" && type !== \"record\" && type !== \"array\") return {};\n let paths: Paths;\n if (type === \"array\") paths = { item: walk(item, `${at}[]`) };\n else if (type === \"record\") paths = { any: walk(value, `${at}.*`) };\n else {\n if (options?.strict === false)\n refuse(\n `the actor schema admits unknown keys at \"${at}\": a path it does not declare would be read`\n );\n paths = {\n keys: new Map(\n Object.entries(entries!)\n .filter(([key]) => !options?.omit?.includes(key))\n .map(([key, entry]) => [\n key,\n walk(entry, at === \"actor\" ? key : `${at}.${key}`),\n ])\n ),\n };\n }\n return options?.array ? { item: paths } : paths;\n}\n\n/** One actor declaration's path vocabulary and binding boundary. */\nexport interface ActorContract {\n readonly hasPath: (path: string) => boolean;\n readonly schema: StandardSchemaV1;\n}\n\n/** Whether a normalized schema takes `undefined`: published, or the literal itself. */\nconst acceptsUndefined = (value: VibSchema): boolean => {\n // A schema that takes `undefined` publishes it; any other has neither key.\n const shape = value as VibSchema & {\n acceptsUndefined?: boolean;\n value?: unknown;\n };\n return (\n shape.acceptsUndefined === true ||\n (shape.type === \"literal\" && shape.value === undefined)\n );\n};\n\n/** Normalize structural actor objects once; native validation owns parsing. */\nfunction bindingSchema(\n input: unknown,\n memo = new WeakMap<object, VibSchema>(),\n open = new Set<object>(),\n at = \"actor\"\n): VibSchema {\n // A viborm/validation schema, or a thunk of one, read structurally: what\n // is not one is refused below by its kind.\n const schema = (typeof input === \"function\" ? input() : input) as VibSchema &\n Walked & {\n readonly key?: VibSchema<string, string>;\n readonly default?: unknown;\n readonly schema?: unknown;\n readonly actions?: readonly {\n readonly type: \"transform\";\n readonly transform: (value: unknown) => unknown;\n }[];\n };\n const held = memo.get(schema);\n if (held !== undefined) return held;\n if (open.has(schema))\n refuse(\n `the actor schema is recursive at \"${at}\": its paths are not finite`\n );\n open.add(schema);\n const child = (value: unknown, path = at) =>\n bindingSchema(value, memo, open, path);\n const { type } = schema;\n let result: VibSchema = schema;\n if (type === \"object\") {\n const { transform, refuse: refusal, ...options } = schema.options ?? {};\n const sparse = options.partial !== false && options.atLeast === undefined;\n // Native required-object parsing is dense. Keep the original sparse\n // shape at the user callbacks and output boundary: absent optionals must\n // not become undefined-valued properties (including in cache identities).\n const prune = (value: unknown): Record<string, unknown> => {\n // The native parser owns this fresh object; preserve its identity for\n // refuse, transform and the result, without touching caller input.\n const parsed = value as Record<string, unknown>;\n for (const key of Object.keys(parsed))\n if (parsed[key] === undefined) delete parsed[key];\n return parsed;\n };\n result = v.object(\n Object.fromEntries(\n Object.entries(schema.entries!).map(([key, value]) => [\n key,\n child(value, at === \"actor\" ? key : `${at}.${key}`),\n ])\n ),\n {\n ...options,\n partial: false,\n refuse: sparse && refusal ? (value) => refusal(prune(value)) : refusal,\n transform: sparse\n ? (value) => {\n // Refuse already saw the pruned object. Its mutations survive,\n // even if it deliberately introduced an undefined property.\n const parsed = refusal ? value : prune(value);\n return transform ? transform(parsed) : parsed;\n }\n : transform,\n }\n );\n } else if (type === \"optional\")\n result = v.optional(child(schema.wrapped), schema.default);\n else if (type === \"nullable\") result = v.nullable(child(schema.wrapped));\n else if (type === \"lazyRef\") result = child(schema.wrapped);\n else if (type === \"array\") result = v.array(child(schema.item));\n else if (type === \"record\")\n result = v.record(schema.key!, child(schema.value));\n else if (type === \"union\" && Array.isArray(schema.options))\n result = v.union(schema.options.map((member) => child(member)));\n else if (type === \"pipe\")\n result = v.pipe(child(schema.schema), ...schema.actions!);\n // These wrappers delegate undefined correctly, but their ordinary object\n // metadata does not publish it. Actor objects require this fact before\n // choosing whether to run a member's validator on a missing key.\n const delegates =\n type === \"union\"\n ? schema.options\n : type === \"pipe\"\n ? [schema.schema]\n : type === \"nullable\"\n ? [schema.wrapped]\n : [];\n if (\n result !== schema &&\n Array.isArray(delegates) &&\n delegates.some((member) => acceptsUndefined(child(member)))\n )\n Object.defineProperty(result, \"acceptsUndefined\", { value: true });\n open.delete(schema);\n memo.set(schema, result);\n return result;\n}\n\n/**\n * The one actor contract supplies both the finite policy path vocabulary and\n * the schema used at binding. Actor objects require their non-optional fields;\n * normalizing structural schemas leaves union selection, defaults, transforms\n * and array/record traversal with their existing native validators.\n */\nexport function actorContract(schema: unknown): ActorContract {\n // Any value: an object schema is told apart by its `type`.\n if ((schema as Walked | undefined)?.type !== \"object\")\n refuse(\"the actor must be a viborm/validation object schema (v.object)\");\n const normalized = bindingSchema(schema);\n const root = walk(normalized, \"actor\");\n return {\n hasPath(path) {\n let at: Paths | undefined = root;\n for (const key of path.split(\".\")) {\n at = at.keys?.get(key) ?? at.any;\n if (at === undefined) return false;\n }\n return true;\n },\n schema: normalized,\n };\n}\n\n/** Whether `T` is one of `Seen`, both ways: a structural subtype is not the same object. */\ntype IsSeen<T, Seen> = true extends (\n Seen extends unknown\n ? [T] extends [Seen]\n ? [Seen] extends [T]\n ? true\n : false\n : false\n : never\n)\n ? true\n : false;\n\n/**\n * Every dotted path of an actor value: a key, or a key and a path below it; a\n * record's keys are any string. The object types already walked stop the walk,\n * so a recursive type ends without a depth number (plan §11.2 F8).\n */\nexport type ActorPaths<T, Seen = never> = T extends readonly unknown[]\n ? never\n : T extends object\n ? IsSeen<T, Seen> extends true\n ? never\n : string extends keyof T\n ? string\n : {\n [K in keyof T & string]-?:\n | K\n | `${K}.${ActorPaths<NonNullable<T[K]>, Seen | T>}`;\n }[keyof T & string]\n : never;\n\n/**\n * The actor a binding takes: what its schema parses to, read only, where an\n * entry whose value may be `undefined` may also be left out (an optional\n * entry's output keeps its key; `v.object`'s input type makes every key\n * optional).\n */\nexport type ActorFacts<T> = T extends readonly (infer Item)[]\n ? readonly ActorFacts<Item>[]\n : T extends Date | ((...args: never[]) => unknown)\n ? T\n : T extends object\n ? {\n readonly [K in keyof T as undefined extends T[K]\n ? never\n : K]: ActorFacts<T[K]>;\n } & {\n readonly [K in keyof T as undefined extends T[K]\n ? K\n : never]?: ActorFacts<T[K]>;\n }\n : T;\n","// The schema-independent predicate language of viborm/permissions. Applications\n// name their own fields, actor paths and authorization conventions.\n\n/** A `where` over a model's relations and the actor's facts, held as data. */\nexport type Where = { readonly [key: string]: unknown };\n/** A boolean grant, a `where`, or a function of its declared action and model. */\nexport type Rule =\n | boolean\n | Where\n | ((action: string, model: PolicyModel) => Rule);\n\n/** What a rule function reads of the model it is evaluated at. */\nexport interface PolicyModel {\n readonly name: string;\n /** Its actions, in declaration order (none for a model the policy does not list). */\n readonly actions: readonly string[];\n}\n\n/** A `where` no row satisfies. Internal compiler identity, not a public helper. */\nexport const FALSE: Where = Object.freeze({ OR: Object.freeze([]) });\n","// The one formula of viborm/permissions (plan §3.2 R1), compiled once per schema:\n//\n// P(M, a) = scopes(M, a) ∧ mandatory(M) ∧ ⋁_{b ⊒ a} rule(M, b)(b)\n//\n// Rule functions are evaluated here for their declared action, and\n// the policy's spellings are lowered to the words of a rule: `{ actor: \"p\" }`\n// in a value position is `arg(\"actor\", \"p\")`, `{ actor: { p: v } }` in a filter\n// a `provided` test of it, `$if` and `$exists` their words, and a relation\n// whose value is an action name the target's predicate at that action,\n// inlined (D7). What comes out is each model's rule entry (K3): its read\n// predicate, its read-gated fields and `$access` facts (D5, D6, K5), its\n// modes, the produced row's placement, moves and acyclic relations (R4, K4),\n// and the predicate each write takes. A placement or a move drops a conjunct\n// another one, or a judgement the same statement makes, provably implies\n// (plan §11.4). The proof reads what each word it wrote stands for.\n\nimport { ClientInitializationError } from \"../errors\";\nimport { check, facts, gate, only } from \"../extensions/judge-words\";\nimport {\n arg,\n exists,\n nothing,\n now,\n provided,\n row,\n when,\n} from \"../extensions/rule-words\";\nimport type { ArgTest, VibORMConfig } from \"../index\";\nimport { type ActorContract, actorContract, refuse } from \"./actor\";\nimport { FALSE, type PolicyModel, type Rule, type Where } from \"./rules\";\n\ntype Schema = VibORMConfig[\"schema\"];\ntype AnyModel = Schema[string];\n\n/** What the compiler reads of a model's declaration. */\ninterface ModelFacts {\n readonly scalars: Readonly<\n Record<\n string,\n {\n readonly \"~\": {\n readonly state: {\n readonly type: string;\n readonly isId?: boolean;\n readonly nullable?: boolean;\n };\n };\n }\n >\n >;\n readonly relations: Readonly<\n Record<\n string,\n {\n readonly \"~\": {\n readonly state: {\n readonly foreignKey?: {\n readonly fields: readonly string[];\n readonly references: readonly string[];\n };\n };\n settleTarget(): unknown;\n };\n }\n >\n >;\n readonly compoundId?: Readonly<Record<string, { readonly entries: object }>>;\n}\n\n/** One model's declaration (plan §1.1). */\nexport interface ModelPolicy {\n readonly mandatory?: Where;\n readonly actions?: { readonly [action: string]: readonly string[] };\n readonly create?: Rule;\n readonly operations?: {\n readonly read?: string;\n readonly update?: string;\n readonly delete?: string;\n };\n readonly fields?: {\n readonly [field: string]: {\n readonly read?: string;\n readonly write?: string;\n };\n };\n readonly domains?: { readonly [name: string]: Rule };\n /** A named action or comma-separated actions' rule: `read`, `read, update`, … */\n readonly [action: string]: Rule | undefined;\n}\n\nexport interface PermissionsConfig {\n /** Who calls: a `viborm/validation` object schema of the request's facts. */\n readonly actor: object;\n readonly mandatory?: Where;\n readonly models: { readonly [model: string]: ModelPolicy };\n /**\n * `\"allow\"` lets a governed read be served from the cache (OD-10). A cached\n * answer was judged when it was stored: a revoked grant or an expired\n * session reaches it only after its TTL. Refused when absent.\n */\n readonly cache?: \"allow\";\n /**\n * The tenant a governed call stays in: on every model with a scalar\n * `field` but the ones `except` names, a set the policy's rules compute\n * over a whole table, where a positive test reads it, holds only the rows\n * whose `field` is the actor's `actor` path (`rows.confine`). Nothing else\n * reads differently. `except` names the models whose rows a rule reads\n * beyond the actor's tenant: a person's memberships of other\n * organizations, a shared catalogue.\n */\n readonly tenant?: {\n readonly field: string;\n readonly actor: string;\n readonly except?: readonly string[];\n };\n}\n\n/**\n * One model's rule entry, as `permissions` hands it to the chain: its read\n * predicate, each field it gates and its `$access` facts, the modes that\n * narrow a call's own rows (`root`), the placement every created row\n * satisfies (R4), and the predicate each write takes: an update writing a\n * protected field its own (R3), one writing a field the placement reads the\n * placement again (a move). An entry part (`read`, `update`, `delete`) whose\n * action the model does not declare takes no row. Predicates are shared by\n * identity wherever they are read.\n */\nexport interface CompiledModel {\n readonly read: {\n readonly where: object;\n readonly fields: { readonly [field: string]: Gate };\n readonly select?: { readonly [key: `$${string}`]: Facts };\n };\n readonly root?: readonly object[];\n readonly create: { readonly check: Check };\n readonly update: {\n readonly where: Only;\n readonly fields: {\n readonly [field: string]: {\n readonly where?: Only;\n readonly check?: Check;\n };\n };\n };\n readonly delete: { readonly where: Only };\n /** The self relations an update keeps acyclic: they need every model compiled. */\n readonly acyclic: () => readonly string[];\n}\ntype Gate = ReturnType<typeof gate<unknown>>;\ntype Facts = ReturnType<typeof facts<string>>;\ntype Check = ReturnType<typeof check<unknown>>;\ntype Only = ReturnType<typeof only<unknown>>;\n\nexport interface CompiledPolicy {\n /** Each admitted scope and its transitive implications, including itself. */\n readonly scopes: Readonly<Record<string, readonly string[]>>;\n /** Every model of the schema: one the policy does not list holds nothing (R9). */\n readonly models: { readonly [model: string]: CompiledModel };\n}\n\n/** The `as` value a call takes when it names none: it narrows nothing. */\nexport const DEFAULT_MODE = \"default\";\n/** The call argument that narrows a call to one action or domain (R8). */\nexport const MODE = \"as\";\n/** The projection key the entry declares on every listed model (D6, OD-2). */\nexport const EVIDENCE_KEY = \"$access\";\n/** The placement's name: the predicate of `create` (R4). */\nconst PLACE = \"$create\";\n\nconst RESERVED = new Set([\n \"mandatory\",\n \"actions\",\n \"operations\",\n \"fields\",\n \"domains\",\n]);\n/** Keys a declaration no longer takes, and what took their place. */\nconst RETIRED: Readonly<Record<string, string>> = {\n within: 'was renamed to \"mandatory\"',\n arms: \"was removed; assign rules to named actions\",\n};\nconst OPERATIONS = new Set([\"read\", \"update\", \"delete\"]);\nconst CRUD = new Set([\"create\", \"read\", \"update\", \"delete\"]);\nconst CONFIG_KEYS = new Set([\n \"actor\",\n \"mandatory\",\n \"models\",\n \"cache\",\n \"tenant\",\n]);\nconst FIELD_KEYS = new Set([\"read\", \"write\"]);\n\nconst LOGICAL = new Set([\"AND\", \"OR\", \"NOT\"]);\n/** A check of another model's rows that reads no column of the row judged. */\nconst EXISTS = \"$exists\";\n/** A row a rule reads: its model, and why a `{ $row, up }` may not cross it. */\ninterface Scope {\n readonly model: string;\n readonly sealed?: boolean;\n}\n/** `{ $row, up }` (a record of these two keys): a column of a row the rule reads, `up` bodies above. */\nconst isEnclosingRow = (\n value: Record<string, unknown>\n): value is { readonly $row: string; readonly up: number } =>\n typeof value.$row === \"string\" &&\n Number.isSafeInteger(value.up) &&\n // A safe integer, which `isSafeInteger` does not tell the types.\n (value.up as number) >= 0;\nconst QUANTIFIERS = new Set([\"is\", \"isNot\", \"some\", \"every\", \"none\"]);\n/**\n * A plain object: a clause or an operator's record, never a value (a Date, a\n * Decimal, bytes). A field reference is a plain object whose only key is a\n * symbol: read as a record it would be `{}`, true everywhere, so an object\n * with a symbol key is a value.\n */\nexport const isRecord = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return (\n (prototype === Object.prototype || prototype === null) &&\n Object.getOwnPropertySymbols(value).length === 0\n );\n};\nconst isActorField = (value: unknown): value is { actor: string } =>\n isRecord(value) &&\n typeof value.actor === \"string\" &&\n Object.keys(value).length === 1;\n\n/** A clause: a `where`, or `false` when it folds false while compiling. */\ntype Clause = Where | false;\nconst isTrue = (clause: Where) => Object.keys(clause).length === 0;\nconst membersOf = (clause: Where, key: \"AND\" | \"OR\"): Where[] =>\n Object.keys(clause).length === 1 && Array.isArray(clause[key])\n ? // A list, checked just above: `and` and `or` write lists of clauses.\n (clause[key] as Where[])\n : [clause];\n/**\n * A rule's record that writes `$if` or `$exists` beside its filters: the one\n * conjunction it was written as, which a conjunction it joins holds whole,\n * and its conjuncts in the order the rule spells them.\n */\nexport const written = new WeakMap<Where, readonly Where[]>();\n\nfunction and(clauses: readonly Clause[]): Clause {\n if (clauses.includes(false)) return false;\n // No clause is `false`: that returned above.\n const kept = (clauses as Where[])\n .filter((clause) => !isTrue(clause))\n .flatMap((clause) =>\n written.has(clause) ? [clause] : membersOf(clause, \"AND\")\n );\n if (kept.length < 2) return kept[0] ?? {};\n return { AND: kept };\n}\n\n/** `cache`'s value at `key`, built once; a build that throws is asked again. */\nconst memo = <K, V>(\n cache: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n build: () => V\n): V => {\n let value = cache.get(key);\n if (value === undefined) cache.set(key, (value = build()));\n return value;\n};\n\n/**\n * What a word the compiler writes stands for, as its proof reads it: an\n * argument's value (its argument and path), a condition on one (the value\n * and its test), another model's rows (the model and the `where` they\n * match), a column of an enclosing row (its column and how many bodies up).\n */\ntype Made =\n | { readonly arg: readonly [control: string, path: unknown] }\n | { readonly provided: readonly [tested: object, test: Where] }\n | { readonly exists: readonly [model: string, body: Where] }\n | { readonly row: readonly [column: string, up: unknown] };\n\n/** A model's admitted action graph, rule assignments and projection meaning. */\ninterface ActionRules {\n readonly rules: ReadonlyMap<\n string,\n { readonly rule: Rule | undefined; readonly source: string }\n >;\n readonly closure: ReadonlyMap<string, readonly string[]>;\n}\n\n/** Resolve grouped rule keys once, before any consumer reads their actions. */\nfunction actionsOf(name: string, policy: ModelPolicy): ActionRules {\n const implies = new Map<string, readonly string[]>(\n Object.entries(policy.actions ?? {})\n );\n const rules = new Map<\n string,\n { readonly rule: Rule | undefined; readonly source: string }\n >();\n // Never reinterpret a key of the declaration, nor an old restriction or\n // grant container, as an action.\n const notAction = (key: string, at: string) => {\n if (Object.hasOwn(RETIRED, key))\n refuse(`${at}: \"${key}\" ${RETIRED[key]}`, name);\n if (RESERVED.has(key))\n refuse(\n `${at}: \"${key}\" is a key of the declaration, not an action`,\n name\n );\n };\n // Only a model's rule keys can group actions. Graph edges name individual\n // actions, so accepting a comma there would create another action.\n for (const action of [...implies.keys(), ...[...implies.values()].flat()])\n if (action.includes(\",\"))\n refuse(\n `models.${name}: \"${action}\" is not an individual action; commas group rules only`,\n name\n );\n\n for (const sourceKey of Object.keys(policy)) {\n if (RESERVED.has(sourceKey)) continue;\n const source = `models.${name}.${sourceKey}`;\n const binding = { rule: policy[sourceKey], source };\n const keys = sourceKey.includes(\",\")\n ? sourceKey\n .split(\",\")\n .map((key) => key.replace(/^[ \\t\\r\\n]+|[ \\t\\r\\n]+$/g, \"\"))\n : [sourceKey];\n for (const key of keys) {\n if (key.length === 0)\n refuse(\n `${source}: an action group cannot contain an empty member`,\n name\n );\n notAction(key, source);\n const previous = rules.get(key);\n if (previous !== undefined)\n refuse(\n `${source}: action \"${key}\" already has a rule at ${previous.source}`,\n name\n );\n rules.set(key, binding);\n if (implies.has(key)) continue;\n // An explicit graph lists every action: unknown members would introduce an undeclared permission.\n if (policy.actions)\n refuse(\n `${source}: neither an action ${name} lists in \\`actions\\` nor a key of the declaration (${[...RESERVED].join(\", \")}); unknown action \"${key}\"`,\n name\n );\n // Without a graph a model's actions are CRUD: any other key is a typo\n // or a custom action, and was never to become a permission unlisted.\n if (!CRUD.has(key))\n refuse(\n `${source}: \"${key}\" is not create, read, update or delete. A custom action is declared in the model's graph (one outside a graph was removed): actions: { read: [], ${key}: [\"read\"] }`,\n name\n );\n implies.set(key, []);\n }\n }\n // An update or a delete grants read by default: whoever may change a row\n // may see it. A create is a placement over a proposed row and implies\n // nothing; custom actions imply only what is declared.\n for (const action of [\"update\", \"delete\"]) {\n const inherited = implies.get(action);\n if (inherited === undefined) continue;\n if (!implies.has(\"read\")) implies.set(\"read\", []);\n if (!inherited.includes(\"read\"))\n implies.set(action, [...inherited, \"read\"]);\n }\n for (const [action, implied] of implies) {\n notAction(action, `models.${name}`);\n for (const next of implied)\n if (!implies.has(next))\n refuse(\n `models.${name}.actions.${action} implies \"${next}\", which ${name} does not declare`,\n name\n );\n }\n // Each action and what it implies, depth first.\n const reach = (action: string, reached: Set<string>): Set<string> => {\n if (!reached.has(action)) {\n reached.add(action);\n for (const next of implies.get(action)!) reach(next, reached);\n }\n return reached;\n };\n return {\n rules,\n closure: new Map(\n [...implies.keys()].map((action) => [\n action,\n [...reach(action, new Set())],\n ])\n ),\n };\n}\n\n/**\n * What a policy's arguments accept, read from the declaration alone: every\n * `as` value (the default, each listed model's actions and domains) and\n * each credential scope with the scopes it implies. A declaration the\n * compiler refuses yields the default alone: applying it refuses it there.\n */\nexport function policyArguments(config: PermissionsConfig): {\n readonly modes: readonly string[];\n readonly scopes: Readonly<Record<string, readonly string[]>>;\n} {\n try {\n const modes = new Set<string>([DEFAULT_MODE]);\n const scopes: Record<string, readonly string[]> = {};\n for (const [name, policy] of Object.entries(config.models)) {\n const { closure } = actionsOf(name, policy);\n for (const [action, implied] of closure) {\n modes.add(action);\n scopes[`${name}.${action}`] = implied.map((next) => `${name}.${next}`);\n }\n for (const domain of Object.keys(policy.domains ?? {})) modes.add(domain);\n }\n return { modes: [...modes], scopes };\n } catch {\n return { modes: [DEFAULT_MODE], scopes: {} };\n }\n}\n\n/** `{ control, path? }`: an argument's value, as a rule may spell one. */\nconst isReference = (\n value: Record<string, unknown>\n): value is { readonly control: string; readonly path?: unknown } =>\n typeof value.control === \"string\" &&\n Object.keys(value).every((key) => key === \"control\" || key === \"path\");\n\n/**\n * Compiles a policy against the schema it governs, every model at once: what\n * `policy.compile(schema)` shows.\n */\nexport function compilePolicy(\n config: PermissionsConfig,\n schema: Schema,\n actor: ActorContract = actorContract(config.actor)\n): CompiledPolicy {\n const compiler = policyCompiler(config, schema, actor);\n return {\n scopes: policyArguments(config).scopes,\n models: Object.fromEntries(\n Object.keys(schema).map((name) => [name, compiler.model(name).entry])\n ),\n };\n}\n\n/**\n * A model's action per entry part and its `as` modes: what applying a policy\n * needs before any query.\n */\ninterface DeclaredModel {\n readonly read?: string;\n readonly update?: string;\n readonly delete?: string;\n /** Its actions, then its domains: each names the predicate of its own name. */\n readonly modes: readonly string[];\n /** What the policy's own whole-table sets of this model hold (`tenant`). */\n readonly bound?: Where | undefined;\n}\n\n/** What a model declares, read without lowering a rule. */\ninterface Declared extends DeclaredModel {\n /**\n * Field → the predicate an update writing it takes (by name): `update`'s,\n * or `$write:<field>` where its write action is another.\n */\n readonly writes: { readonly [field: string]: string };\n readonly reads: { readonly [field: string]: string };\n /** Field → its move (filled when the model compiles). */\n readonly moves?: { readonly [field: string]: string };\n}\n/** A model the policy does not list declares nothing. */\nconst UNLISTED: Declared = {\n modes: [],\n writes: {},\n reads: {},\n};\n\n/**\n * One policy against one schema, compiled a model at a time. Building it\n * checks everything the declaration says without lowering a rule (its keys,\n * models, action graphs, operations, fields and `as` names), so those\n * refusals come when the policy is applied; a rule's own refusals (a field,\n * an actor path, a relation's action, a rule that reads itself) come when\n * its model is first compiled. Models compile into one shared state, so each\n * predicate is lowered once whatever order they are asked in, and the output\n * is the same as compiling every model at once.\n */\nexport interface PolicyCompiler {\n /** Every model of the schema: its parts' actions and modes. */\n readonly declared: { readonly [model: string]: DeclaredModel };\n /** One model compiled: one the policy does not list holds nothing (R9). */\n model(name: string): Compiled;\n}\n\nconst NO_RELATIONS: readonly string[] = [];\n/** One model compiled: its predicates by name, which `acyclic` walks, and its entry. */\nexport interface Compiled {\n readonly predicates: ReadonlyMap<string, Where>;\n readonly entry: CompiledModel;\n}\n\nexport function policyCompiler(\n config: PermissionsConfig,\n schema: Schema,\n actor: ActorContract = actorContract(config.actor)\n): PolicyCompiler {\n const made = new WeakMap<object, Made>();\n /**\n * One compilation's structural keys: two values share a key exactly when they\n * are the same value, numbers by `Object.is` (NaN and ±Infinity are no\n * `null`), bigints, valid dates by their instant, arrays and records member by\n * member; anything else by identity. A record or an array is keyed once, so\n * equality, duplicate removal and the implication cache cost one lookup\n * however often a shared clause is met. Keys hold only for one compilation,\n * which never mutates what it reads.\n */\n const shapes = new Map<string, string>();\n const known = new WeakMap<object, string>();\n // Opaque values (a Decimal, bytes, a symbol) are equal only to themselves.\n const opaque = new Map<unknown, string>();\n let next = 0;\n const keyOf = (value: unknown): string => {\n if (typeof value === \"number\")\n return Object.is(value, -0) ? \"n-0\" : `n${value}`;\n if (typeof value === \"string\") return `s${JSON.stringify(value)}`;\n if (typeof value === \"bigint\") return `b${value}`;\n if (value == null || typeof value === \"boolean\") return `p${value}`;\n // A date is read at each comparison; an invalid one equals only itself.\n if (value instanceof Date && !Number.isNaN(value.getTime()))\n return `d${value.getTime()}`;\n if (typeof value !== \"object\") {\n let key = opaque.get(value);\n if (key === undefined) opaque.set(value, (key = `o${next++}`));\n return key;\n }\n let key = known.get(value);\n if (key !== undefined) return key;\n // A word is what it stands for; another value equals only itself.\n const word = made.get(value);\n if (word !== undefined) key = `w${keyOf(word)}`;\n else if (Array.isArray(value) || isRecord(value)) {\n const shape = Array.isArray(value)\n ? `[${value.map(keyOf).join(\",\")}]`\n : `{${Object.keys(value)\n .sort()\n .map((field) => `${JSON.stringify(field)}:${keyOf(value[field])}`)\n .join(\",\")}}`;\n key = shapes.get(shape);\n if (key === undefined) shapes.set(shape, (key = `#${next++}`));\n } else key = `o${next++}`;\n known.set(value, key);\n return key;\n };\n const same = (x: unknown, y: unknown): boolean =>\n (x === y && typeof x !== \"number\") || keyOf(x) === keyOf(y);\n /** `members` without a repeated value, in order. */\n const distinct = <T>(members: readonly T[]): T[] => {\n const seen = new Set<string>();\n return members.filter((member) => {\n const key = keyOf(member);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n };\n const or = (clauses: readonly Clause[]): Clause => {\n const kept = clauses.filter((clause): clause is Where => clause !== false);\n if (kept.length === 0) return false;\n if (kept.some(isTrue)) return {};\n // Rules have already been evaluated at their declaring actions. Equal\n // resulting branches contribute once without suppressing callback evaluation.\n const flat = distinct(kept.flatMap((member) => membersOf(member, \"OR\")));\n return flat.length === 1 ? flat[0]! : { OR: flat };\n };\n /** What `word` stands for, kept for the proof. */\n const wrote = (word: object, stands: Made): Where => {\n made.set(word, stands);\n // A word stands where a filter or a value goes: the rule's admission\n // reads it in that place, its members hidden from every type.\n return word as Where;\n };\n const madeOf = (value: unknown): Made | undefined =>\n typeof value === \"object\" && value !== null ? made.get(value) : undefined;\n /** A filter: a `where`, or a word that stands for one. */\n const isClause = (value: unknown): value is Where =>\n isRecord(value) || madeOf(value) !== undefined;\n /** An argument's value: the actor's, or the call's scopes. */\n const ref = (control: string, path?: unknown) =>\n // The rule's admission refuses a path that is not a string.\n wrote(arg(control, path as string | undefined), {\n arg: [control, path],\n });\n /** True only where the argument's value passes the test. */\n const condition = (control: string, path: unknown, test: Where) => {\n // The rule's admission refuses a path that is not a string.\n const tested = arg(control, path as string | undefined);\n // The rule's admission checks the test and refuses another shape.\n return wrote(provided(tested, test as ArgTest), {\n provided: [wrote(tested, { arg: [control, path] }), test],\n });\n };\n for (const key of Object.keys(config))\n if (!CONFIG_KEYS.has(key))\n refuse(\n key === \"levels\"\n ? 'levels was removed: declare the graph on each model instead, actions: { read: [], update: [\"read\"], full: [\"update\"] }'\n : `\"${key}\" is not a key of the policy (${[...CONFIG_KEYS].join(\", \")})`\n );\n for (const name of Object.keys(config.models))\n if (!Object.hasOwn(schema, name))\n refuse(`models.${name}: the schema has no such model`, name);\n\n const names = new Map<AnyModel, string>(\n Object.entries(schema).map(([name, model]) => [model, name])\n );\n const stateOf = (name: string) =>\n // What compiling reads of a model's state: a narrower view of it.\n schema[name]![\"~\"].state as unknown as ModelFacts;\n const relationOf = (name: string, relation: string) =>\n Object.hasOwn(stateOf(name).relations, relation)\n ? stateOf(name).relations[relation]![\"~\"]\n : undefined;\n const targetOf = (name: string, relation: string) => {\n const settled = relationOf(name, relation)?.settleTarget();\n // A relation settles to a model of the schema, or none, which has no name.\n return names.get(settled as AnyModel);\n };\n\n const actions = new Map<string, ActionRules>(\n Object.entries(config.models).map(([name, policy]) => [\n name,\n actionsOf(name, policy),\n ])\n );\n const models = new Map<string, PolicyModel>();\n const modelOf = (name: string): PolicyModel =>\n memo(models, name, () =>\n Object.freeze({\n name,\n actions: Object.freeze([...(actions.get(name)?.closure.keys() ?? [])]),\n })\n );\n\n // The declared rule owns callback evaluation. Inheritance reuses that exact\n // predicate; credential scope gates apply only to the requested action.\n const rules = new Map<string, Clause>();\n const predicates = new Map<string, Clause>();\n /** Every `P(M, a)`: inlined anywhere, its `{ $row, up }` never leaves it. */\n const inlined = new WeakSet<Where>();\n const open: string[] = [];\n const scope = (name: string, action: string): Where => ({\n OR: [\n condition(\"scopes\", \"unrestricted\", { equals: true }),\n condition(\"scopes\", \"allowed\", { has: `${name}.${action}` }),\n ],\n });\n const ruleAt = (name: string, action: string): Clause =>\n memo(rules, `${name}.${action}`, () => {\n const binding = actions.get(name)!.rules.get(action);\n return binding?.rule === undefined\n ? false\n : lower(name, action, binding.rule, binding.source);\n });\n const restrictions = new Map<string, Clause>();\n // Lowered at no action: a callback in it is refused where it stands.\n const restriction = (name: string): Clause =>\n memo(restrictions, name, () =>\n and([\n lower(\n name,\n undefined,\n config.models[name]!.mandatory ?? {},\n `models.${name}.mandatory`\n ),\n lower(name, undefined, config.mandatory ?? {}, \"mandatory\"),\n ])\n );\n const P = (name: string, action: string): Clause => {\n const key = `${name}.${action}`;\n return memo(predicates, key, () => {\n if (open.includes(key))\n refuse(\n `models.${key} reads itself: ${[...open.slice(open.indexOf(key)), key].join(\" → \")}`,\n name\n );\n open.push(key);\n // A compiler outlives a refusal (a model compiles at its first call, and\n // the next call asks again): the walk is unwound whatever happens.\n try {\n const declared = actions.get(name)!;\n const inherited =\n declared.rules.get(action)?.rule === false\n ? []\n : [...declared.closure].flatMap(([from, reaches]) =>\n reaches.includes(action) ? [from] : []\n );\n const branches = inherited.map((from) => ruleAt(name, from));\n const granted = or(branches);\n const clause = and([restriction(name), absorb(name, granted)]);\n if (clause !== false) inlined.add(clause);\n return clause;\n } finally {\n open.pop();\n }\n });\n };\n /**\n * A disjunction without a member another member provably contains: where\n * `x ⇒ y`, `x ∨ y` is `y`, so `x` is dropped (the later of two equivalent\n * members). Rules evaluated at their declared action and inherited (a\n * grouped `\"read, update\": capped(rule)`) differ per action only by what\n * the higher action narrows (`role in [...]`, a coverage list), so the\n * narrower branches fold into the widest one, as the plan's one-branch\n * form had them, with the same rows. Sound, never complete (§11.4 D13):\n * what the prover cannot show stays.\n */\n const absorb = (name: string, clause: Clause): Clause => {\n if (clause === false || !Array.isArray(clause.OR)) return clause;\n // lower/or normalize siblings into AND, so OR is the only root key here.\n const members = clause.OR as Where[];\n const kept = prune(\n name,\n members,\n [...members.keys()],\n (at, dropped) =>\n members.some(\n (wider, other) =>\n other !== at &&\n !dropped.has(other) &&\n implies(name, members[at]!, wider) &&\n // Equivalent members keep the earlier one.\n !(other > at && implies(name, wider, members[at]!))\n ),\n (remaining) => and([restriction(name), or(remaining)])\n );\n return kept.length === 1 ? kept[0]! : { OR: kept };\n };\n\n /** A path the actor schema declares, or the refusal naming where it is read. */\n const path = (at: string, read: unknown) => {\n if (typeof read === \"string\" && !actor.hasPath(read))\n refuse(\n `${at} reads actor path \"${read}\", which the actor schema does not declare`\n );\n };\n /** Each model's tenant bound (`tenant`), checked once: undefined where the model has no such field. */\n const tenantOf = (\n tenant: PermissionsConfig[\"tenant\"]\n ): ((name: string) => Where | undefined) => {\n if (tenant === undefined) return () => undefined;\n const except = tenant?.except ?? [];\n if (\n !isRecord(tenant) ||\n typeof tenant.field !== \"string\" ||\n typeof tenant.actor !== \"string\" ||\n !Array.isArray(except) ||\n except.some((name) => typeof name !== \"string\") ||\n Object.keys(tenant).some(\n (key) => ![\"field\", \"actor\", \"except\"].includes(key)\n )\n )\n refuse(\n \"tenant is { field, actor, except? }: the scalar field that names a row's tenant, the actor path that names the caller's, and the models read beyond it\"\n );\n path(\"tenant.actor\", tenant.actor);\n const holds = (name: string) =>\n Object.hasOwn(stateOf(name).scalars, tenant.field);\n if (!Object.keys(schema).some(holds))\n refuse(\n `tenant.field: no model of the schema has a scalar field \"${tenant.field}\"`\n );\n for (const name of except)\n if (!(Object.hasOwn(schema, name) && holds(name)))\n refuse(\n `tenant.except names ${name}, which is not a model of the schema with a scalar field \"${tenant.field}\"`\n );\n const bound: Where = { [tenant.field]: ref(\"actor\", tenant.actor) };\n return (name) =>\n holds(name) && !except.includes(name) ? bound : undefined;\n };\n /**\n * A value position: the actor's fields and the other spellings of a value\n * as their words, checked. A document compared whole (a JSON value) is a\n * literal: an actor value is the operand itself, never an object inside it.\n */\n const value = (\n at: string,\n input: unknown,\n enclosing: (row: { readonly $row: string; readonly up: number }) => void,\n spelled = true\n ): unknown => {\n // A list's members keep `{ actor }` as written and check no path.\n if (Array.isArray(input))\n return input.map((item) => value(at, item, enclosing, false));\n if (spelled && isActorField(input)) {\n path(at, input.actor);\n return ref(\"actor\", input.actor);\n }\n if (!isRecord(input)) return input;\n if (spelled && input.control === \"actor\") path(at, input.path);\n if (isReference(input)) return ref(input.control, input.path);\n const keys = Object.keys(input);\n if (typeof input.$row === \"string\" && keys.length === 2) {\n // `up` counts bodies: another value would read the rule's own row.\n if (!isEnclosingRow(input))\n refuse(\n `${at}: { $row, up } takes a column and a whole number, 0 or more`\n );\n enclosing(input);\n // `up` was checked to be a whole number above.\n return wrote(row(input.$row, input.up as number), {\n row: [input.$row, input.up],\n });\n }\n if (input.now === true && keys.length === 1) return now;\n return Object.fromEntries(\n keys.map((key) => [\n key,\n key === \"equals\" &&\n isRecord(input[key]) &&\n !isReference(input[key]) &&\n !isActorField(input[key])\n ? input[key]\n : value(at, input[key], enclosing, spelled),\n ])\n );\n };\n /** `{ actor: { p: v } }` in a filter: one condition per leaf. */\n const conditions = (at: string, facts: unknown, prefix = \"\"): Where[] => {\n if (!isRecord(facts))\n refuse(\n `${at} tests the actor with a value that is not an object of its facts`\n );\n // An empty object tests nothing: it would hold for every actor.\n if (Object.keys(facts).length === 0)\n refuse(\n `${at} tests the actor${prefix ? ` at \"${prefix.slice(0, -1)}\"` : \"\"} with an empty object`\n );\n return Object.entries(facts).flatMap(([key, fact]) => {\n const read = `${prefix}${key}`;\n if (isRecord(fact)) return conditions(at, fact, `${read}.`);\n path(at, read);\n if (fact !== null && typeof fact === \"object\")\n refuse(\n `${at} tests actor path \"${read}\" against ${Array.isArray(fact) ? \"a list\" : \"a value that is not a literal\"}`\n );\n return [\n condition(\n \"actor\",\n read,\n fact === null ? { exists: false } : { equals: fact }\n ),\n ];\n });\n };\n\n /** A rule of `name` read at `action` (written at `at`), lowered to the `where` vocabulary. */\n const lower = (\n name: string,\n action: string | undefined,\n rule: unknown,\n at: string,\n scopes: readonly Scope[] = [{ model: name }]\n ): Clause => {\n if (typeof rule === \"boolean\") return rule ? {} : false;\n if (typeof rule === \"function\") {\n if (action === undefined)\n refuse(\n `${at}: mandatory is action-independent and cannot contain callbacks`,\n name\n );\n // Whatever a rule function throws is its model's refusal, like any\n // other mistake in a rule: it fails that model, never another.\n let evaluated: unknown;\n try {\n evaluated = rule(action, modelOf(name));\n } catch (error) {\n if (error instanceof ClientInitializationError) throw error;\n refuse(`${at}: the rule function threw at \"${action}\"`, name, error);\n }\n return lower(name, action, evaluated, at, scopes);\n }\n if (!isRecord(rule))\n refuse(\n `${at}: a rule is a boolean, a where object or a function of the action`,\n name\n );\n const state = stateOf(name);\n const out: Record<string, unknown> = {};\n const also: Clause[] = [];\n let tested: Where | undefined;\n let existing: Where | undefined;\n for (const [key, member] of Object.entries(rule)) {\n if (LOGICAL.has(key)) {\n const list = (Array.isArray(member) ? member : [member]).map((item) =>\n lower(name, action, item, at, scopes)\n );\n const folded =\n key === \"OR\"\n ? or(list)\n : and(\n key === \"AND\"\n ? list\n : list.map((item) =>\n item === false ? {} : isTrue(item) ? false : { NOT: item }\n )\n );\n if (folded === false) return false;\n also.push(folded);\n } else if (\n key === \"actor\" &&\n !(\n Object.hasOwn(state.scalars, key) ||\n Object.hasOwn(state.relations, key)\n )\n ) {\n also.push(...conditions(at, member));\n } else if (key === \"$if\") {\n const { control, path: read, ...test } = isRecord(member) ? member : {};\n // A name the words take for the call's instant: refused here, in\n // the policy's own terms.\n if (typeof control !== \"string\")\n refuse(\n `${at}: $if names one control and exactly one test of it`,\n name\n );\n if (control === \"actor\") path(at, read);\n // `$if` names exactly one control: checked above.\n tested = condition(control as string, read, test);\n } else if (key === EXISTS) {\n // Another model's rows, read at their own model: action names are\n // that model's predicates (D7), as in a relation's body.\n const models = isRecord(member) ? Object.keys(member) : [];\n const [model] = models;\n if (models.length !== 1 || !Object.hasOwn(schema, model!))\n refuse(\n `${at}: $exists names exactly one model of the schema and the where its rows must match`,\n name\n );\n // One body below this row, joined to nothing.\n const body = lower(model!, action, (member as Where)[model!], at, [\n ...scopes,\n { model: model! },\n ]);\n if (body === false) return false;\n existing = wrote(exists({ [model!]: body }), {\n exists: [model!, body],\n });\n } else if (member === undefined) {\n // A filter's `undefined` filters nothing: in a rule it would grant\n // every row, as an absent value never should.\n refuse(\n `${at}: ${key} is compared with undefined, which holds for every row; compare with null, a literal or an actor value`,\n name\n );\n } else if (targetOf(name, key) !== undefined) {\n const lowered = relation(name, action, key, member, at, scopes);\n if (lowered === false) return false;\n if (lowered !== undefined) out[key] = lowered;\n } else {\n out[key] = value(at, member, (operand) =>\n enclosingRow(name, key, operand, at, scopes)\n );\n }\n }\n const words = [tested, existing].filter((word) => word !== undefined);\n if (words.length === 0) return and([out, ...also]);\n const held: Where =\n isTrue(out) && words.length === 1\n ? words[0]!\n : { AND: [...(isTrue(out) ? [] : [out]), ...words] };\n written.set(\n held,\n Object.keys(rule).flatMap((key) =>\n key === \"$if\"\n ? [tested!]\n : key === EXISTS\n ? [existing!]\n : Object.hasOwn(out, key)\n ? [{ [key]: out[key] }]\n : []\n )\n );\n return and([held, ...also]);\n };\n\n /**\n * A `{ $row, up }` in a scalar's operand names a column of a row the rule\n * reads (its own at `up: 0`), never past the rule's root, an `$exists`\n * body's, or a recursive relation's body.\n */\n const enclosingRow = (\n name: string,\n key: string,\n operand: { readonly $row: string; readonly up: number },\n at: string,\n scopes: readonly Scope[]\n ): void => {\n const fail = (why: string) =>\n refuse(\n `${at}: ${key} compares { $row: ${JSON.stringify(operand.$row)}, up: ${operand.up} }${why}`,\n name\n );\n const index = scopes.length - 1 - operand.up;\n if (index < 0)\n fail(\n `, which reaches past the rule (${scopes.length - 1} relation bodies deep here)`\n );\n const crossed = scopes.slice(index + 1).find((scope) => scope.sealed);\n if (crossed) fail(` across a recursive relation to ${crossed.model}`);\n const owner = scopes[index]!.model;\n if (!Object.hasOwn(stateOf(owner).scalars, operand.$row))\n fail(`, and ${owner} has no scalar field \"${operand.$row}\"`);\n };\n /** A relation filter: an action name is the target's predicate (D7). */\n const relation = (\n name: string,\n action: string | undefined,\n key: string,\n member: unknown,\n at: string,\n scopes: readonly Scope[]\n ): unknown => {\n const target = targetOf(name, key)!;\n if (typeof member === \"string\") {\n if (!modelOf(target).actions.includes(member))\n refuse(\n `${at} reads ${key} at \"${member}\", which ${target} does not declare`,\n name\n );\n const held = P(target, member);\n return held && { is: held };\n }\n // A field reference, a Date or any other value is not a relation filter.\n if (typeof member === \"object\" && member !== null && !isRecord(member))\n refuse(\n `${at} filters ${key} with a value that is not a filter object, an action name or null`,\n name\n );\n if (!isRecord(member)) return member;\n if (!Object.keys(member).some((op) => QUANTIFIERS.has(op)))\n return lower(target, action, member, at, [...scopes, { model: target }]);\n const out: Record<string, unknown> = {};\n let requiresEmpty = false;\n const scope = { model: target, sealed: member.recurse !== undefined };\n for (const [op, body] of Object.entries(member)) {\n if (!(QUANTIFIERS.has(op) && body !== null)) {\n out[op] = body;\n continue;\n }\n const lowered = lower(target, action, body, at, [...scopes, scope]);\n // A false body: `is`/`some` hold nowhere, `isNot`/`none` everywhere,\n // `every` only where nothing is related.\n if (lowered !== false) out[op] = lowered;\n else if (op === \"is\" || op === \"some\") return false;\n else if (op === \"every\") requiresEmpty = true;\n }\n // `every false` requires an empty relation, which implies any `none`\n // clause. Apply it last so property order cannot weaken the conjunction.\n if (requiresEmpty) out.none = {};\n return Object.keys(out).length === 0 ? undefined : out;\n };\n\n /**\n * Whether `a` implies `b`, both read at `name`, by their structure alone:\n * sound, never complete (a `false` only keeps a conjunct). It is what lets\n * a placement and a move say once what the statement already judges, so\n * the heaviest writes fit a provider's statement limits (plan §11.4).\n */\n const implied = new Map(\n Object.keys(schema).map((name) => [\n name,\n new Map<string, Map<string, boolean>>(),\n ])\n );\n const implies = (name: string, a: Where, b: Where): boolean => {\n if (a === b) return true;\n // Keyed by structure: simplification rebuilds equal guards many times.\n const byModel = implied.get(name)!;\n const left = keyOf(a);\n let row = byModel.get(left);\n if (row === undefined) byModel.set(left, (row = new Map()));\n const right = keyOf(b);\n let answer = row.get(right);\n if (answer === undefined) row.set(right, (answer = provable(name, a, b)));\n return answer;\n };\n const provable = (name: string, a: Where, b: Where): boolean => {\n const right = conjuncts(b);\n if (right.length !== 1)\n return right.every((member) => implies(name, a, member));\n const left = conjuncts(a);\n const [key, given] = headOf(left[0] ?? { AND: [] });\n const [wanted, value] = headOf(right[0]!);\n // `or` writes every alternative as a list.\n if (left.length === 1 && key === \"OR\")\n return (given as Where[]).every((member) => implies(name, member, b));\n if (\n wanted === \"OR\" &&\n // The same: a list of alternatives.\n (value as Where[]).some((member) => implies(name, a, member))\n )\n return true;\n if (left.length !== 1)\n return left.some((member) => implies(name, member, b));\n if (key !== wanted) return false;\n const mine = madeOf(left[0]);\n const theirs = madeOf(right[0]);\n if (mine && theirs && \"provided\" in mine && \"provided\" in theirs) {\n const [tested, test] = mine.provided;\n const [other, wider] = theirs.provided;\n return (\n same(mine, theirs) ||\n (same(tested, other) && narrower(test, wider, \"hasSome\"))\n );\n }\n if (mine && theirs && \"exists\" in mine && \"exists\" in theirs) {\n // EXISTS is monotone: a narrower body finds a row only where a wider one does.\n const [left, narrow] = mine.exists;\n const [right, wide] = theirs.exists;\n return left === right && implies(left, narrow, wide);\n }\n if (!(isRecord(given) && isRecord(value))) return same(given, value);\n if (key === \"NOT\") return implies(name, value, given);\n const target = targetOf(name, key);\n if (target === undefined)\n return (\n same(given, value) ||\n narrower(given, value, \"hasSome\") ||\n narrower(given, value, \"in\")\n );\n // A relation: the same walk, its body implied at the target. Negative\n // quantifiers reverse containment; their wrappers are never scalar keys.\n const ops = [...QUANTIFIERS].filter((op) => Object.hasOwn(value, op));\n if (ops.length === 0) return implies(target, given, value);\n return ops.every(\n (op) =>\n isRecord(given[op]) &&\n isRecord(value[op]) &&\n same(without(given, op), without(value, op)) &&\n (op === \"none\" || op === \"isNot\"\n ? implies(target, value[op], given[op])\n : implies(target, given[op], value[op]))\n );\n };\n /**\n * A conjunct's one key and its member: what a word stands for under the\n * key a rule spells it with.\n */\n const headOf = (clause: Where): [string, unknown] => {\n const word = madeOf(clause);\n return word === undefined\n ? Object.entries(clause)[0]!\n : [\"exists\" in word ? EXISTS : \"$if\", clause];\n };\n /** Stable decomposition lets the implication cache reuse each owned member. */\n const conjunctions = new WeakMap<Where, readonly Where[]>();\n const conjuncts = (clause: Where): readonly Where[] => {\n const known = conjunctions.get(clause);\n if (known !== undefined) return known;\n const members =\n written.get(clause) ??\n (!isRecord(clause) ||\n (Object.keys(clause).length === 1 && !Object.hasOwn(clause, \"AND\"))\n ? [clause]\n : Object.entries(clause).flatMap(([key, member]) =>\n // `and` writes every conjunction as a list.\n key === \"AND\"\n ? (member as Where[]).flatMap(conjuncts)\n : [{ [key]: member }]\n ));\n conjunctions.set(clause, members);\n return members;\n };\n const without = (record: Where, key: string) => {\n const { [key]: _dropped, ...rest } = record;\n return rest;\n };\n /** `{ op: S1, …rest }` against `{ op: S2, …rest }`, with S1 ⊆ S2. */\n const narrower = (given: Where, value: Where, op: string) =>\n Array.isArray(given[op]) &&\n Array.isArray(value[op]) &&\n same(without(given, op), without(value, op)) &&\n // Both lists, checked above.\n (given[op] as unknown[]).every((item) =>\n // The same list.\n (value[op] as unknown[]).some((other) => same(item, other))\n );\n /**\n * R6 reads parameters only after call conditions have folded. A read's\n * guard therefore includes both AND's false siblings and OR's true\n * siblings. Flat sets lose this distinction and can widen a policy.\n * These summaries describe only folding, never row truth or SQL.\n */\n interface ReadSummary {\n readonly yes: Clause;\n readonly no: Clause;\n readonly reads: ReadonlyMap<string, Clause>;\n }\n /**\n * Guards are rebuilt for every candidate a simplification tries, so each\n * one is shared: an equal guard is the first one built, and its negation\n * is derived once.\n */\n const builtGuards = new Map<string, Where>();\n const shared = (guard: Clause): Clause => {\n if (guard === false) return guard;\n const key = keyOf(guard);\n const held = builtGuards.get(key);\n if (held !== undefined) return held;\n builtGuards.set(key, guard);\n return guard;\n };\n const negations = new WeakMap<Where, Clause>();\n const negate = (guard: Clause): Clause => {\n if (guard === false) return {};\n if (isTrue(guard)) return false;\n if (Object.keys(guard).length === 1 && isClause(guard.NOT))\n return guard.NOT;\n let negation = negations.get(guard);\n if (negation === undefined)\n negations.set(\n guard,\n (negation = Array.isArray(guard.AND)\n ? combined(\n false,\n guard.AND.map((member: Where) => negate(member))\n )\n : Array.isArray(guard.OR)\n ? combined(\n true,\n guard.OR.map((member: Where) => negate(member))\n )\n : shared({ NOT: guard }))\n );\n return negation;\n };\n /**\n * One combination of shared guards, built once per distinct operands.\n * Boolean guards, unlike row predicates, have two-valued logic: a\n * conjunction drops repeated factors, never distributes over a disjunction\n * nor expands a truth table.\n */\n const combinations = new Map<string, Clause>();\n const combined = (\n conjunction: boolean,\n guards: readonly Clause[]\n ): Clause => {\n let key = `${conjunction}`;\n for (const operand of guards)\n key += operand === false ? \" F\" : ` ${keyOf(operand)}`;\n let guard = combinations.get(key);\n if (guard === undefined) {\n const all = conjunction ? and(guards) : or(guards);\n combinations.set(\n key,\n (guard = shared(\n conjunction && all && Array.isArray(all.AND)\n ? // A list, checked just above.\n and(distinct(all.AND as Where[]))\n : all\n ))\n );\n }\n return guard;\n };\n const falseSummary: ReadSummary = {\n yes: false,\n no: {},\n reads: new Map(),\n };\n const atomic = (\n reads: ReadonlyMap<string, Clause> = new Map()\n ): ReadSummary => ({\n yes: false,\n no: false,\n reads,\n });\n const combineReads = (\n conjunction: boolean,\n summaries: readonly ReadSummary[]\n ): ReadSummary => {\n const yes = combined(\n conjunction,\n summaries.map((part) => part.yes)\n );\n const no = combined(\n !conjunction,\n summaries.map((part) => part.no)\n );\n const live = negate(conjunction ? no : yes);\n const reads = new Map<string, Clause>();\n for (const part of summaries)\n for (const [key, guard] of part.reads)\n reads.set(\n key,\n combined(false, [\n reads.get(key) ?? false,\n combined(true, [live, guard]),\n ])\n );\n return { yes, no, reads };\n };\n /** Each clause's summary per model: a shared clause is walked once. */\n const summaries = new Map(\n Object.keys(schema).map((name) => [\n name,\n new WeakMap<object, ReadSummary | null>(),\n ])\n );\n const parameterKey = (\n operand: unknown,\n spread: boolean\n ): string | undefined => {\n const word = madeOf(operand);\n return word && \"arg\" in word\n ? JSON.stringify([word.arg[0], word.arg[1] ?? null, spread])\n : undefined;\n };\n const containsParameter = (operand: unknown): boolean =>\n parameterKey(operand, false) !== undefined ||\n (Array.isArray(operand)\n ? operand.some(containsParameter)\n : isRecord(operand) && Object.values(operand).some(containsParameter));\n const readOperators = new Set([\n \"equals\",\n \"not\",\n \"in\",\n \"notIn\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"contains\",\n \"startsWith\",\n \"endsWith\",\n \"has\",\n \"hasSome\",\n \"hasEvery\",\n \"isEmpty\",\n ]);\n /** Ordinary scalar filters contain no call conditions. Exotic operands\n * are left alone rather than guessing how a provider reads their values. */\n const scalarReads = (operand: unknown): ReadSummary | null => {\n const direct = parameterKey(operand, false);\n if (direct !== undefined) return atomic(new Map([[direct, {}]]));\n // An enclosing row's column and the call's instant are written as\n // records of their own, which no read operator spells.\n if (operand === now || madeOf(operand)) return null;\n if (!isRecord(operand)) return containsParameter(operand) ? null : atomic();\n const reads = new Map<string, Clause>();\n for (const [operator, value] of Object.entries(operand)) {\n if (operator === \"mode\" || operator === \"path\") continue;\n if (!readOperators.has(operator)) return null;\n const spread = operator === \"in\" || operator === \"notIn\";\n const key = parameterKey(value, spread);\n if (key !== undefined) reads.set(key, {});\n else if (operator === \"not\" || operator === \"equals\") {\n const nested = scalarReads(value);\n if (nested === null) return null;\n for (const [read, guard] of nested.reads) reads.set(read, guard);\n } else if (spread && Array.isArray(value)) {\n for (const item of value) {\n const read = parameterKey(item, false);\n if (read !== undefined) reads.set(read, {});\n else if (containsParameter(item)) return null;\n }\n } else if (containsParameter(value)) return null;\n }\n // Modifier-only objects (and `{}`) can also be literal JSON. Do not infer\n // folding without the scalar codec's admission decision.\n if (Object.keys(operand).every((key) => key === \"mode\" || key === \"path\"))\n return null;\n return atomic(reads);\n };\n /** The summary of one key of a clause read at `name`, or null where unsupported. */\n const partOf = (\n name: string,\n key: string,\n value: unknown\n ): ReadSummary | null => {\n if (LOGICAL.has(key)) {\n const nested: ReadSummary[] = [];\n for (const body of Array.isArray(value) ? value : [value]) {\n const summary = summarizeReads(name, body);\n if (summary === null) return null;\n nested.push(\n key === \"NOT\"\n ? { yes: summary.no, no: summary.yes, reads: summary.reads }\n : summary\n );\n }\n return combineReads(key !== \"OR\", nested);\n }\n if (Object.hasOwn(stateOf(name).scalars, key)) return scalarReads(value);\n const target = targetOf(name, key);\n if (target === undefined) return null;\n const bodies: unknown[] = [];\n if (\n isRecord(value) &&\n Object.keys(value).some((op) => QUANTIFIERS.has(op))\n ) {\n for (const [op, body] of Object.entries(value))\n if (QUANTIFIERS.has(op)) bodies.push(body);\n else if (op !== \"recurse\" && op !== \"self\") return null;\n } else bodies.push(value);\n const relations: ReadSummary[] = [];\n for (const body of bodies) {\n // A relation keeps its quantifier even when its body folds constant;\n // a null one (`relation: null`, `is: null`) reads nothing.\n const summary = body === null ? atomic() : summarizeReads(target, body);\n if (summary === null) return null;\n relations.push(atomic(summary.reads));\n }\n return combineReads(true, relations);\n };\n const summarizeReads = (\n name: string,\n clause: unknown\n ): ReadSummary | null => {\n if (clause === false) return falseSummary;\n if (!isClause(clause)) return null;\n // A condition guards what it is read with; another model's rows are\n // read like a positive relation's body, wherever the clause is.\n const word = madeOf(clause);\n // A word in a clause's place is a condition or another model's rows:\n // an argument's value and an enclosing row's column stand for values.\n if (word !== undefined) {\n if (\"exists\" in word) {\n const summary = summarizeReads(...word.exists);\n return summary && combineReads(true, [atomic(summary.reads)]);\n }\n return combineReads(true, [\n { yes: clause, no: negate(clause), reads: new Map() },\n ]);\n }\n const cache = summaries.get(name)!;\n const known = cache.get(clause);\n if (known !== undefined) return known;\n const parts: ReadSummary[] = [];\n for (const [key, value] of Object.entries(clause)) {\n const part = partOf(name, key, value);\n if (part === null) {\n cache.set(clause, null);\n return null;\n }\n parts.push(part);\n }\n const result = combineReads(true, parts);\n cache.set(clause, result);\n return result;\n };\n const provesGuard = (name: string, a: Clause, b: Clause): boolean =>\n a === false ||\n (b !== false && (isTrue(b) || same(a, b) || implies(name, a, b)));\n\n /** Equal conditional reads preserve missing/null AND non-list spread\n * refusals. This simplifier injects no guards. An unsupported\n * shape or unproved equivalence simply retains the original expression. */\n const preservesReads = (\n name: string,\n before: Clause,\n after: Clause\n ): boolean => {\n const left = summarizeReads(name, before);\n const right = summarizeReads(name, after);\n if (left === null || right === null) return false;\n // Both callers only delete clauses: no new parameter can appear after.\n // Entries survive even when their guard is false, so guard changes still\n // have to prove equivalence in both directions.\n for (const [key, a] of left.reads) {\n const b = right.reads.get(key) ?? false;\n if (!(provesGuard(name, a, b) && provesGuard(name, b, a))) return false;\n }\n return true;\n };\n /**\n * `members` without each one `covered` says another contains, tried in\n * `order`: a member is dropped only where the judgement `whole` builds of\n * the members left retains the same conditional parameter reads (R6).\n */\n const prune = (\n name: string,\n members: readonly Where[],\n order: readonly number[],\n covered: (at: number, dropped: ReadonlySet<number>) => boolean,\n whole: (members: readonly Where[]) => Clause\n ): Where[] => {\n const dropped = new Set<number>();\n let judgement = whole(members);\n for (const at of order) {\n if (!covered(at, dropped)) continue;\n const reduced = whole(\n members.filter((_, index) => index !== at && !dropped.has(index))\n );\n if (!preservesReads(name, judgement, reduced)) continue;\n judgement = reduced;\n dropped.add(at);\n }\n return members.filter((_, at) => !dropped.has(at));\n };\n /**\n * The conjunction of `clauses` without a member another one implies (or\n * one of `given`, which the same statement already judges), the later\n * first, where the whole judgement, `given` included, keeps its reads.\n */\n const conjoin = (\n name: string,\n clauses: readonly Clause[],\n given: readonly Where[] = []\n ): Clause => {\n const all = and(clauses);\n if (all === false) return false;\n const members = conjuncts(all);\n return and(\n prune(\n name,\n members,\n [...members.keys()].reverse(),\n (at, dropped) => {\n const covers = (other: Where) => implies(name, other, members[at]!);\n return (\n given.some(covers) ||\n members.some(\n (other, index) =>\n index !== at && !dropped.has(index) && covers(other)\n )\n );\n },\n (remaining) => and([...given, ...remaining])\n )\n );\n };\n\n /**\n * Each foreign key `name` holds, with what R4 asks of a value written to\n * it: null where every field of the key may be, or a target the actor\n * views (`P(T, read)`, false where T holds none: R9, fail closed).\n */\n const keysOf = (name: string) =>\n Object.entries(stateOf(name).relations).flatMap(([relation, declared]) => {\n const key = declared[\"~\"].state.foreignKey;\n if (key === undefined) return [];\n const target = targetOf(name, relation)!;\n const action = declarations.get(target)?.read;\n const held = action ? P(target, action) : false;\n const visible = held && { [relation]: { is: held } };\n const nullable = key.fields.every(\n (field) => stateOf(name).scalars[field]?.[\"~\"].state.nullable === true\n );\n const clause = nullable\n ? or([and(key.fields.map((field) => ({ [field]: null }))), visible])\n : visible;\n return [{ relation, fields: key.fields, clause }];\n });\n /**\n * The fields of the rule's own row its bodies compare (`{ $row, up:\n * depth }`). An inlined predicate is relative to its own root and never\n * reaches past it, so it is not walked; a shared clause is walked once per\n * depth.\n */\n const rootReads = (\n name: string,\n clause: unknown,\n depth: number,\n into: Set<string>,\n seen = new Map<object, Set<number>>()\n ): void => {\n const word = madeOf(clause);\n if (word && \"row\" in word) {\n if (word.row[1] === depth) into.add(word.row[0]);\n return;\n }\n if (typeof clause !== \"object\" || clause === null) return;\n // Below the root, an inlined predicate's references stay inside it; at\n // depth 0 it may be a branch of the rule itself (a `P` an action shares).\n if (depth > 0 && inlined.has(clause as Where)) return;\n const depths = seen.get(clause) ?? new Set<number>();\n if (depths.has(depth)) return;\n seen.set(clause, depths.add(depth));\n if (Array.isArray(clause))\n for (const item of clause) rootReads(name, item, depth, into, seen);\n else if (word && \"exists\" in word)\n rootReads(word.exists[0], word.exists[1], depth + 1, into, seen);\n else if (isRecord(clause))\n for (const [key, member] of Object.entries(clause)) {\n const target = LOGICAL.has(key) ? undefined : targetOf(name, key);\n if (target === undefined || !isRecord(member))\n rootReads(name, member, depth, into, seen);\n else if (Object.keys(member).some((op) => QUANTIFIERS.has(op))) {\n for (const op of QUANTIFIERS)\n if (isRecord(member[op]))\n rootReads(target, member[op], depth + 1, into, seen);\n }\n // The to-one shorthand: the body is the related row's own filter.\n else rootReads(target, member, depth + 1, into, seen);\n }\n };\n /**\n * The fields of `name`'s row a clause read at `name` reads: a scalar, the\n * fields a relation joins on (its key, or on the other side the fields of\n * `name` any key references), and a self relation's body where `self`\n * reads the row itself.\n */\n const ownFields = (name: string, clause: unknown, into: Set<string>) => {\n // A condition and another model's rows read no field of the row.\n if (!isRecord(clause)) return;\n for (const [key, member] of Object.entries(clause)) {\n if (LOGICAL.has(key))\n for (const item of Array.isArray(member) ? member : [member])\n ownFields(name, item, into);\n else if (targetOf(name, key) === undefined) into.add(key);\n else {\n const own = relationOf(name, key)!.state.foreignKey;\n if (own !== undefined) for (const field of own.fields) into.add(field);\n else\n for (const other of names.values())\n for (const declared of Object.values(stateOf(other).relations)) {\n const foreign = declared[\"~\"].state.foreignKey;\n if (\n foreign !== undefined &&\n // A relation settles to a model of the schema.\n names.get(declared[\"~\"].settleTarget() as AnyModel) === name\n )\n for (const field of foreign.references) into.add(field);\n }\n if (isRecord(member) && member.self === true)\n for (const op of QUANTIFIERS)\n if (isRecord(member[op])) ownFields(name, member[op], into);\n }\n }\n };\n\n /** One name per predicate of a model: actions, domains, the placement, moves. */\n const unclaimed = (\n names: { has(key: string): boolean },\n key: string,\n at: string,\n name: string\n ) => {\n if (names.has(key))\n refuse(\n `${at}: an action, a domain, the placement or a move already has the name \"${key}\"`,\n name\n );\n };\n // Every check that lowers no rule runs before any model is compiled: the\n // declaration's names (operations, fields, domains, the `as` names), so a\n // misspelt one is refused when the policy is applied, wherever it is.\n const declarations = new Map<string, Declared>();\n for (const name of Object.keys(config.models)) {\n const policy = config.models[name]!;\n const model = modelOf(name);\n const declared = (role: string, action: string | undefined) => {\n if (action !== undefined && !model.actions.includes(action))\n refuse(\n `models.${name}.${role} names \"${action}\", which ${name} does not declare. Declared actions: ${model.actions.join(\", \") || \"none\"}. Add its rule or choose a declared action.`,\n name\n );\n return action;\n };\n // The names `claim` gives out below, but for the moves, which need the\n // placement lowered: the same refusals, at the same places.\n const claimed = new Set<string>(model.actions);\n const claimName = (key: string, at: string) => {\n unclaimed(claimed, key, at, name);\n claimed.add(key);\n };\n const operations = policy.operations ?? {};\n for (const operation of Object.keys(operations))\n if (!OPERATIONS.has(operation))\n refuse(\n `models.${name}.operations.${operation}: not a configurable operation; use read, update or delete (create always uses its own grant)`,\n name\n );\n // The action each entry part takes (K3, OD-3): `operations`, else read,\n // update and delete; a part whose action the model does not declare\n // takes none. Adding actions never changes an operation mapping.\n const byPart: { read?: string; update?: string; delete?: string } = {};\n for (const part of [\"read\", \"update\", \"delete\"] as const) {\n const action = declared(`operations.${part}`, operations[part]) ?? part;\n if (model.actions.includes(action)) byPart[part] = action;\n }\n const writes: Record<string, string> = {};\n const reads: Record<string, string> = {};\n const state = stateOf(name);\n for (const [field, entry] of Object.entries(policy.fields ?? {})) {\n const unknown = isRecord(entry)\n ? Object.keys(entry).find((key) => !FIELD_KEYS.has(key))\n : \"\";\n if (unknown !== undefined)\n refuse(\n `models.${name}.fields.${field}${unknown ? `.${unknown}` : \"\"}: a field entry takes only read and write`,\n name\n );\n const { read, write } = entry;\n if (\n !(\n Object.hasOwn(state.scalars, field) ||\n Object.hasOwn(state.relations, field)\n )\n )\n refuse(\n `models.${name}.fields.${field}: ${name} has no such field`,\n name\n );\n if (write !== undefined) {\n declared(`fields.${field}.write`, write);\n if (write === byPart.update) writes[field] = write;\n else {\n const protectedWrite = `$write:${field}`;\n claimName(protectedWrite, `models.${name}.fields.${field}.write`);\n writes[field] = protectedWrite;\n }\n }\n // A key, a foreign key or a relation is refused by K5's admission.\n if (read === undefined) continue;\n reads[field] = declared(`fields.${field}.read`, read)!;\n }\n claimName(PLACE, `models.${name}.create`);\n const domains = Object.keys(policy.domains ?? {});\n for (const domain of domains)\n claimName(domain, `models.${name}.domains.${domain}`);\n const modes = [...model.actions, ...domains];\n // One `as` name space for every model: the default is no action's.\n if (modes.includes(DEFAULT_MODE))\n refuse(\n `models.${name}: \"${DEFAULT_MODE}\" is the mode a call takes by default, not an action or a domain`,\n name\n );\n declarations.set(name, {\n ...byPart,\n modes,\n writes,\n reads,\n });\n }\n\n /** One listed model's predicates, by name, and its rule entry. */\n const compileModel = (name: string): Compiled => {\n const policy = config.models[name]!;\n const model = modelOf(name);\n const declared = declarations.get(name)!;\n const { writes, ...byPart } = declared;\n const named = new Map<string, Where>();\n // The declaration's names were claimed when the policy was applied; a\n // move's name is new here, and a domain may take one.\n const claim = (key: string, at: string, clause: Where) => {\n unclaimed(named, key, at, name);\n named.set(key, clause);\n };\n for (const action of model.actions)\n named.set(action, and([P(name, action), scope(name, action)]) || FALSE);\n // Field protection narrows the operation's grant. Core chooses one\n // write predicate per field, so compose both permissions here rather\n // than letting a field grant replace a denied or absent update grant.\n for (const [field, { write }] of Object.entries(policy.fields ?? {}))\n if (writes[field] === `$write:${field}`)\n named.set(\n writes[field],\n and([\n byPart.update === undefined ? false : named.get(byPart.update)!,\n named.get(write!)!,\n ]) || FALSE\n );\n // Creation is a named action evaluated on the proposed row. Its placement\n // adds target visibility; moves reuse the row rule without requiring a\n // create credential scope for an update.\n const create = P(name, \"create\");\n const keys = keysOf(name);\n named.set(\n PLACE,\n conjoin(name, [\n create,\n scope(name, \"create\"),\n ...keys.map(({ clause }) => clause),\n ]) || FALSE\n );\n // A move (OD-14): an update writing a field the placement reads is\n // placed again; one writing a key, its target visible.\n const placed = new Set<string>();\n if (create !== false) {\n rootReads(name, create, 0, placed);\n ownFields(name, create, placed);\n }\n const moves: Record<string, string> = {};\n for (const field of new Set([\n ...placed,\n ...keys.flatMap(({ fields }) => fields),\n ])) {\n const move = `move:${field}`;\n const holding = keys.filter(({ fields }) => fields.includes(field));\n // The new row is also judged at what judged the old one (R4), which a\n // move need not say: the read action, and the field's write action when\n // every spelling of the write (the field, a relation holding it) takes\n // the same one (R3).\n const spelled = new Set(\n [field, ...holding.map(({ relation }) => relation)].map(\n (written) => writes[written] ?? byPart.update\n )\n );\n const judged = [byPart.read, ...(spelled.size === 1 ? spelled : [])]\n .filter((action) => action !== undefined)\n .map((action) => named.get(action)!);\n claim(\n move,\n `models.${name}.fields.${field}`,\n conjoin(\n name,\n [\n placed.has(field) ? create : {},\n ...holding.map(({ clause }) => clause),\n ],\n judged\n ) || FALSE\n );\n moves[field] = move;\n }\n for (const [domain, rule] of Object.entries(policy.domains ?? {})) {\n const at = `models.${name}.domains.${domain}`;\n claim(domain, at, lower(name, \"read\", rule, at) || FALSE);\n }\n return entryOf(name, named, { ...declared, moves });\n };\n /**\n * A model's rule entry from its predicates by name: its read action, each\n * field it gates and its `$access`, each write part at its action (an\n * action it does not grant takes no row), the fields whose write takes\n * its own action, the placement of a created row and the moves of an\n * updated one, and the modes that narrow its call's own rows (the\n * default and the read action narrow nothing: `read` holds in every\n * mode).\n */\n const entryOf = (\n name: string,\n named: ReadonlyMap<string, Where>,\n { writes, reads, moves = {}, modes, ...byPart }: Declared\n ): Compiled => {\n const P = (key: string | undefined): object =>\n key === undefined ? nothing : named.get(key)!;\n const names = modelOf(name).actions;\n const root = modes\n .filter((mode) => mode !== byPart.read)\n .map((mode) => when(arg(MODE), mode, P(mode)));\n return {\n predicates: named,\n entry: {\n read: {\n where: P(byPart.read),\n fields: Object.fromEntries(\n Object.entries(reads).map(([field, key]) => [field, gate(P(key))])\n ),\n // Per row, always one boolean for each admitted action.\n ...(names.length > 0 && {\n select: {\n [EVIDENCE_KEY]: facts(\n Object.fromEntries(names.map((fact) => [fact, P(fact)]))\n ),\n },\n }),\n },\n ...(root.length > 0 && { root }),\n create: { check: check(P(PLACE)) },\n update: {\n where: only(P(byPart.update)),\n fields: Object.fromEntries(\n [...new Set([...Object.keys(writes), ...Object.keys(moves)])].map(\n (field) => [\n field,\n {\n ...(writes[field] !== undefined && {\n where: only(P(writes[field])),\n }),\n ...(moves[field] !== undefined && {\n check: check(P(moves[field])),\n }),\n },\n ]\n )\n ),\n },\n delete: { where: only(P(byPart.delete)) },\n acyclic: () => acyclicAt(name),\n },\n };\n };\n\n // A Map: a model may be named `constructor`.\n const compiled = new Map<string, Compiled>();\n /** `name` compiled, once: an unlisted model holds nothing (R9). */\n const modelAt = (name: string): Compiled =>\n memo(compiled, name, () =>\n Object.hasOwn(config.models, name)\n ? compileModel(name)\n : entryOf(name, new Map([[PLACE, FALSE]]), UNLISTED)\n );\n // R4: a self key a predicate recurses over never takes a parent inside\n // the row's own subtree. Any model's predicate may recurse over another's\n // relation, so this is the one fact that needs the whole policy compiled.\n let recursed: ReadonlyMap<string, readonly string[]> | undefined;\n const acyclicAt = (name: string): readonly string[] => {\n if (recursed === undefined) {\n // A model whose rules are refused judges nothing, and every model\n // that inlines one of its predicates is refused with it: what the\n // others recurse over is complete without it.\n for (const each of Object.keys(schema))\n try {\n modelAt(each);\n } catch (error) {\n if (!(error instanceof ClientInitializationError)) throw error;\n }\n // Per model, the self relations holding a key that some compiled\n // predicate recurses over, wherever it is read.\n const found = new Map<string, string[]>();\n // Per model, the clauses already walked there (P is shared, D7).\n const seen = new Map<string, WeakSet<object>>();\n const walk = (name: string, clause: unknown): void => {\n const word = madeOf(clause);\n if (word && \"exists\" in word) walk(...word.exists);\n const walked = memo(seen, name, () => new WeakSet());\n if (!isRecord(clause) || walked.has(clause)) return;\n walked.add(clause);\n for (const [key, member] of Object.entries(clause)) {\n if (LOGICAL.has(key)) {\n for (const item of Array.isArray(member) ? member : [member])\n walk(name, item);\n continue;\n }\n const target = targetOf(name, key);\n if (target === undefined || !isRecord(member)) continue;\n if (\n target === name &&\n member.recurse !== undefined &&\n relationOf(name, key)!.state.foreignKey !== undefined\n ) {\n const list = memo(found, name, () => []);\n if (!list.includes(key)) list.push(key);\n }\n const bodies = [...QUANTIFIERS].filter((op) =>\n Object.hasOwn(member, op)\n );\n for (const body of bodies.length === 0\n ? [member]\n : bodies.map((op) => member[op]))\n walk(target, body);\n }\n };\n for (const [name, model] of compiled)\n for (const clause of model.predicates.values()) walk(name, clause);\n recursed = found;\n }\n return recursed.get(name) ?? NO_RELATIONS;\n };\n const related = tenantOf(config.tenant);\n return {\n declared: Object.fromEntries(\n Object.keys(schema).map((name) => {\n const { writes, reads, ...declared } =\n declarations.get(name) ?? UNLISTED;\n return [name, { ...declared, bound: related(name) }];\n })\n ),\n model: modelAt,\n };\n}\n","// viborm/permissions: one predicate per (model, action), judged in the statement\n// (docs/architecture/rbac-extension-plan.md). An ordinary definition applied\n// through public capabilities; compiling it reads the schema's declarations\n// through the internal `[\"~\"]` accessors.\n//\n// This file is the entry: `permissions(config)` checks the actor schema at once and\n// compiles the policy against the schema it governs. The policy's types are\n// opaque predicates (never a model's `where` type: the 1.2.0 TS2589 lesson);\n// what the types check is the declaration's names: models, fields and actions\n// against the schema and each other, actor paths against the actor schema.\n\nimport type { Operations } from \"../client/exports\";\nimport { ForbiddenError } from \"../errors\";\nimport { args, bound, oneOf } from \"../extensions/args\";\nimport { call } from \"../extensions/call\";\nimport { within } from \"../extensions/confine\";\nimport { extension } from \"../extensions/extension\";\nimport { lazy } from \"../extensions/judge-words\";\nimport { methods } from \"../extensions/methods-part\";\nimport { models as everyOperation, selecting, target } from \"../extensions/on\";\nimport { rule } from \"../extensions/rule\";\nimport type {\n AnyTarget,\n ClientSchema,\n EmptyFacts,\n Extension,\n Facts,\n PlacedArgument,\n Target,\n VibORMConfig,\n} from \"../index\";\nimport type { InferOutput } from \"../validation\";\nimport { type ActorFacts, type ActorPaths, actorContract } from \"./actor\";\nimport {\n type CompiledPolicy,\n compilePolicy,\n DEFAULT_MODE,\n type EVIDENCE_KEY,\n MODE,\n type ModelPolicy,\n type PermissionsConfig,\n type PolicyCompiler,\n policyArguments,\n policyCompiler,\n} from \"./compile\";\nimport type { PolicyModel, Where } from \"./rules\";\n\nexport type { ActorFacts, ActorPaths } from \"./actor\";\nexport type {\n CompiledModel,\n CompiledPolicy,\n ModelPolicy,\n PermissionsConfig,\n} from \"./compile\";\nexport type { PolicyModel, Rule, Where } from \"./rules\";\n\ntype Schema = VibORMConfig[\"schema\"];\n\n// =============================================================================\n// ACTIONS: what each model declares, and the names that must be among them\n// =============================================================================\n\ntype Reserved = \"mandatory\" | \"actions\" | \"operations\" | \"fields\" | \"domains\";\n/** A model's actions when it declares no `actions` graph. */\ntype Crud = \"create\" | \"read\" | \"update\" | \"delete\";\n\ntype RuleKeys<M> = Exclude<keyof M & string, Reserved>;\ntype Space = \" \" | \"\\t\" | \"\\r\" | \"\\n\";\ntype Trim<S extends string> = S extends `${Space}${infer Rest}`\n ? Trim<Rest>\n : S extends `${infer Rest}${Space}`\n ? Trim<Rest>\n : S;\ntype SplitActions<S extends string> = S extends `${infer Head},${infer Tail}`\n ? Trim<Head> | SplitActions<Trim<Tail>>\n : S;\n\n/** Groups contribute their individual actions, never a combined action name. */\ntype DeclaredActions<M> =\n | (M extends { readonly actions: infer A } ? keyof A & string : never)\n | SplitActions<RuleKeys<M>>;\ntype ActionsOf<M> =\n | DeclaredActions<M>\n | (Extract<DeclaredActions<M>, \"update\" | \"delete\"> extends never\n ? never\n : \"read\");\n\ntype InvalidGroup<\n S extends string,\n Seen extends string = never,\n> = S extends `${infer Head},${infer Tail}`\n ? Trim<Head> extends \"\" | Reserved | \"within\" | \"arms\" | Seen\n ? S\n : InvalidGroup<Trim<Tail>, Seen | Trim<Head>>\n : [Seen] extends [never]\n ? never\n : S extends \"\" | Reserved | \"within\" | \"arms\" | Seen\n ? S\n : never;\n\ntype InvalidRuleKeys<M> = {\n [K in RuleKeys<M>]:\n | ([InvalidGroup<K>] extends [never] ? never : K)\n | ([\n Extract<SplitActions<K>, SplitActions<Exclude<RuleKeys<M>, K>>>,\n ] extends [never]\n ? never\n : K);\n}[RuleKeys<M>];\ntype InvalidActionName<S> = S extends string\n ? S extends `${string},${string}` | \"within\" | \"arms\"\n ? S\n : never\n : never;\n\ntype Values<T> = T extends object ? T[keyof T] : never;\ntype NamedActions<M> =\n | Values<M extends { readonly operations: infer O } ? O : never>\n | Values<\n M extends { readonly fields: infer F }\n ? { [K in keyof F]: Values<F[K]> }\n : never\n >\n | (M extends { readonly actions: infer A }\n ? Values<{\n [K in keyof A]: A[K] extends readonly (infer N)[] ? N : never;\n }>\n : never);\n\n/**\n * Retired declaration keys, and rules absent from the model's action list:\n * its explicit graph, else create, read, update and delete. A declaration\n * still widened to its constraint (while a callback in it is inferred) has\n * no keys of its own to check.\n */\ntype UnlistedKeys<M> =\n | Extract<RuleKeys<M>, \"within\" | \"arms\">\n | InvalidRuleKeys<M>\n | (M extends { readonly actions: infer A }\n ?\n | InvalidActionName<keyof A>\n | Exclude<SplitActions<RuleKeys<M>>, keyof A & string>\n : string extends RuleKeys<M>\n ? never\n : Exclude<SplitActions<RuleKeys<M>>, Crud>);\n\ntype UnknownActions<Config extends PermissionsConfig> = {\n [K in keyof Config[\"models\"] & string]: Exclude<\n NamedActions<Config[\"models\"][K]> | UnlistedKeys<Config[\"models\"][K]>,\n | Exclude<ActionsOf<Config[\"models\"][K]>, UnlistedKeys<Config[\"models\"][K]>>\n | undefined\n > extends infer Unknown extends string\n ? [Unknown] extends [never]\n ? never\n : `${K}: ${Unknown}`\n : never;\n}[keyof Config[\"models\"] & string];\n\n// =============================================================================\n// ACTOR PATHS: the ones the declaration spells, against the actor schema\n// =============================================================================\n\n/** Required keys only: an optional key belongs to a payload type, never walked. */\ntype RequiredKeys<T> = {\n [K in keyof T]-?: Record<never, never> extends Pick<T, K> ? never : K;\n}[keyof T];\n\n/**\n * The actor paths a declaration spells: `{ actor: \"path\" }` values and\n * `{ actor: { path: value } }` conditions, found by a walk over the\n * declaration's literal (functions and widened predicates are opaque).\n */\ntype SpelledActorPaths<T> = T extends readonly (infer Item)[]\n ? SpelledActorPaths<Item>\n : T extends (...args: never[]) => unknown\n ? never\n : T extends object\n ? string extends keyof T\n ? never\n :\n | ControlPath<T>\n | {\n [K in RequiredKeys<T> & string]: K extends \"actor\"\n ? T[K] extends string\n ? T[K]\n : ConditionPaths<T[K]>\n : SpelledActorPaths<T[K]>;\n }[RequiredKeys<T> & string]\n : never;\n\n/** Explicit actor parameters and `$if` conditions use the same path vocabulary. */\ntype ControlPath<T> = T extends {\n readonly control: \"actor\";\n readonly path: infer Path extends string;\n}\n ? Path\n : never;\n\ntype ConditionPaths<T> = T extends object\n ? string extends keyof T\n ? never\n : {\n [K in RequiredKeys<T> & string]: T[K] extends object\n ? K | `${K}.${ConditionPaths<T[K]>}`\n : K;\n }[RequiredKeys<T> & string]\n : never;\n\ntype TenantActorPath<Config> = Config extends {\n readonly tenant: { readonly actor: infer Path extends string };\n}\n ? Path\n : never;\ntype UnknownActorPaths<Config extends PermissionsConfig> = Exclude<\n | SpelledActorPaths<Config[\"models\"] | Config[\"mandatory\"]>\n | TenantActorPath<Config>,\n ActorPaths<InferOutput<Config[\"actor\"]>>\n>;\n\ntype ConfigKey = \"actor\" | \"mandatory\" | \"models\" | \"cache\" | \"tenant\";\n\n/** `unknown` when the declaration's names agree; else a member naming the first disagreement. */\ntype DeclarationCheck<Config extends PermissionsConfig> = [\n Exclude<keyof Config, ConfigKey>,\n] extends [never]\n ? ActorAndActionCheck<Config>\n : { readonly \"unknown policy key\": Exclude<keyof Config, ConfigKey> };\n\ntype ActorAndActionCheck<Config extends PermissionsConfig> = [\n UnknownActorPaths<Config>,\n] extends [never]\n ? [UnknownActions<Config>] extends [never]\n ? unknown\n : { readonly \"undeclared action\": UnknownActions<Config> }\n : { readonly \"unknown actor path\": UnknownActorPaths<Config> };\n\n// =============================================================================\n// SCHEMA: the model and field names the declaration spells\n// =============================================================================\n\ntype ScalarsOf<M> = M extends {\n readonly \"~\": { readonly state: { readonly scalars: infer S } };\n}\n ? keyof S\n : never;\ntype RelationsOf<M> = M extends {\n readonly \"~\": { readonly state: { readonly relations: infer R } };\n}\n ? keyof R\n : never;\ntype CreateKeys<M> = M extends { readonly create: infer C }\n ? C extends boolean | ((...args: never[]) => unknown)\n ? never\n : keyof C\n : never;\n\ntype UnknownFields<\n S extends Schema,\n Models extends PermissionsConfig[\"models\"],\n> = {\n [K in keyof Models & keyof S & string]: Exclude<\n | (Models[K] extends { readonly fields: infer F } ? keyof F : never)\n | CreateKeys<Models[K]>,\n | ScalarsOf<S[K]>\n | RelationsOf<S[K]>\n | \"AND\"\n | \"OR\"\n | \"NOT\"\n | \"actor\"\n | \"$if\"\n | \"$exists\"\n > extends infer Unknown extends string\n ? [Unknown] extends [never]\n ? never\n : `${K}.${Unknown}`\n : never;\n}[keyof Models & keyof S & string];\n\n/** `unknown` when every model and field the declaration names is in the schema. */\ntype SchemaCheck<\n S extends Schema,\n Models extends PermissionsConfig[\"models\"],\n> = string extends keyof S\n ? unknown\n : [Exclude<keyof Models, keyof S>] extends [never]\n ? [UnknownFields<S, Models>] extends [never]\n ? unknown\n : { readonly \"unknown field\": UnknownFields<S, Models> }\n : { readonly \"unknown model\": Exclude<keyof Models, keyof S> };\n\n// =============================================================================\n// THE ENTRY: one extension (plan §1.1; K7(b))\n// =============================================================================\n\nconst NAME = \"viborm.permissions\";\n\ntype Listed<Config extends PermissionsConfig> = keyof Config[\"models\"] & string;\ntype ActionOf<\n Config extends PermissionsConfig,\n K extends Listed<Config>,\n> = ActionsOf<Config[\"models\"][K]>;\ntype DomainsOf<M> = M extends { readonly domains: infer D }\n ? keyof D & string\n : never;\n/** Every `as` value: the default, and each listed model's actions and domains. */\ntype ModeOf<Config extends PermissionsConfig> =\n | typeof DEFAULT_MODE\n | {\n [K in Listed<Config>]:\n | ActionOf<Config, K>\n | DomainsOf<Config[\"models\"][K]>;\n }[Listed<Config>];\n\n/**\n * `$as`, declared apart (inline, the factory's contextual type makes `Self`\n * void) as a type, not an interface, so it is a method record.\n */\ntype ScopeOf<Config extends PermissionsConfig> = {\n [K in Listed<Config>]: `${K}.${ActionOf<Config, K>}`;\n}[Listed<Config>];\n\ntype AsMethod<Actor, Scope extends string = string> = {\n /**\n * This client with the actor bound (K6): every call of the view is judged\n * for it. Validated once, here, against the policy's actor schema.\n */\n $as<Self>(this: Self, actor: Actor, scopes?: readonly Scope[]): Self;\n};\n\n/** The fields a model's declaration read-gates (D5). */\ntype GatedOf<M> = M extends { readonly fields: infer F }\n ? {\n [K in keyof F]: F[K] extends { readonly read: string } ? K : never;\n }[keyof F] &\n string\n : never;\n\n/**\n * What the types read of a listed model's rule entry (its `projected` fact): its\n * projection key and its actions (K5's projected overloads), and its\n * read-gated fields (the gated default omit). The predicates stay opaque.\n */\ntype ModelProjection<\n Config extends PermissionsConfig,\n K extends Listed<Config>,\n> = {\n readonly predicates: {\n readonly [name: string]: { readonly [field: string]: unknown };\n };\n} & ([ActionOf<Config, K>] extends [never]\n ? unknown\n : {\n readonly evidence: {\n readonly as: typeof EVIDENCE_KEY;\n readonly names: readonly ActionOf<Config, K>[];\n };\n }) &\n ([GatedOf<Config[\"models\"][K]>] extends [never]\n ? unknown\n : {\n readonly reads: {\n readonly [F in GatedOf<Config[\"models\"][K]>]: string;\n };\n });\n\n/**\n * The policy's arguments as the delegates read them: its mode, on every\n * operation that selects rows. `actor` and `scopes` are bound: no call\n * passes them.\n */\ntype PolicyArguments<Config extends PermissionsConfig> = {\n readonly [MODE]: PlacedArgument<\n ModeOf<Config>,\n PropertyKey,\n Exclude<Operations, \"create\" | \"createMany\">\n >;\n};\n\n/**\n * What applying the policy adds: its arguments, every model of the client\n * governed (a to-one relation reads `| null`), the projection key and the\n * read-gated fields of each listed model, and `$as`.\n */\ntype PermissionsFacts<\n T extends AnyTarget,\n Config extends PermissionsConfig,\n> = Facts<\n AsMethod<ActorFacts<InferOutput<Config[\"actor\"]>>, ScopeOf<Config>>,\n Record<never, never>,\n PolicyArguments<Config>,\n keyof ClientSchema<T[\"config\"]> & string,\n never,\n Record<never, never>,\n Record<never, never>,\n false,\n { readonly [K in Listed<Config>]: ModelProjection<Config, K> }\n>;\n\nexport interface Policy<Config extends PermissionsConfig> {\n readonly config: Config;\n /**\n * The policy compiled against the schema it governs (R1): per model, the\n * rule entry the extension applies, and each credential scope with the\n * scopes it implies. Refusals are `ClientInitializationError`s naming the\n * declaration's path. Public for inspection.\n */\n compile<S extends Schema>(\n schema: S & SchemaCheck<S, Config[\"models\"]>\n ): CompiledPolicy;\n}\n\nconst READS = /^(find|count|aggregate|groupBy|exist)/;\nconst CREATES = /^create/;\nconst UPDATES = /^update/;\n\n/**\n * The action a root operation needs its model to grant (R9, K4), named by\n * its family; an operation of no other family deletes. An upsert is not asked\n * here: each of its arms is judged where it runs, the update where it locates\n * its row and the create in its statement.\n */\nconst actionOf = (operation: string) =>\n READS.test(operation)\n ? \"read\"\n : CREATES.test(operation)\n ? \"create\"\n : UPDATES.test(operation)\n ? \"update\"\n : \"delete\";\n\n/**\n * Every model's modes, alike in name (one argument): the default and the\n * model's read action narrow nothing (`read` already ANDs with every mode,\n * K3); another of its actions or domains narrows by its predicate (R8); a\n * mode it does not declare holds nothing, and a root call naming it is\n * refused before it runs (R9).\n */\ninterface ScopeValues {\n readonly unrestricted: boolean;\n readonly allowed: readonly string[];\n}\nexport interface ScopeSchema {\n readonly \"~standard\": {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: {\n readonly input: readonly string[] | undefined;\n readonly output: ScopeValues;\n };\n validate(\n input: unknown\n ):\n | { readonly value: ScopeValues }\n | { readonly issues: readonly { readonly message: string }[] };\n };\n}\n\n/** Admit the credential once at binding, using the compiler's action closure. */\nfunction scopeSchema(\n implications: Readonly<Record<string, readonly string[]>>\n): ScopeSchema {\n return {\n \"~standard\": {\n version: 1,\n vendor: NAME,\n validate(input) {\n if (input === undefined)\n return { value: { unrestricted: true, allowed: [] } };\n if (!Array.isArray(input))\n return {\n issues: [\n { message: \"Scopes must be an array of model.permission names\" },\n ],\n };\n const allowed = new Set<string>();\n for (const scope of input) {\n if (typeof scope !== \"string\" || !Object.hasOwn(implications, scope))\n return {\n issues: [\n {\n message: `Unknown permission scope: ${typeof scope === \"string\" ? scope : \"expected a string\"}`,\n },\n ],\n };\n for (const implied of implications[scope]!) allowed.add(implied);\n }\n return { value: { unrestricted: false, allowed: [...allowed] } };\n },\n },\n };\n}\n\n/** No client: what an extension written apart from one is built against. */\ntype Untyped = Target<\n VibORMConfig<Record<never, never>>,\n AnyTarget[\"state\"],\n EmptyFacts\n>;\n\n/** Declaration context is field names, not the recursive operation payload. */\ntype PolicyValue<Actor> =\n | string\n | number\n | bigint\n | boolean\n | null\n | Date\n | object\n | {\n readonly actor?: ActorPaths<InferOutput<Actor>>;\n readonly [key: string]: PolicyValue<Actor> | undefined;\n };\n\ntype ModelRelations<Model> = Model extends {\n readonly \"~\": { readonly state: { readonly relations: infer Relations } };\n}\n ? Relations\n : never;\n\ntype ContextualRelation<\n Relation,\n Actor,\n Dynamic extends boolean = true,\n> = Relation extends {\n readonly \"~\": {\n readonly state: {\n readonly target: { readonly getter: () => infer Target };\n };\n };\n}\n ?\n | string\n | (ContextualWhere<Target, Actor, Dynamic> & {\n readonly is?: ContextualRule<Target, Actor, Dynamic> | null;\n readonly isNot?: ContextualRule<Target, Actor, Dynamic> | null;\n readonly some?: ContextualRule<Target, Actor, Dynamic>;\n readonly every?: ContextualRule<Target, Actor, Dynamic>;\n readonly none?: ContextualRule<Target, Actor, Dynamic>;\n })\n : Where | string;\n\ntype ContextualWhere<Model, Actor, Dynamic extends boolean = true> = Where & {\n readonly [Field in ScalarsOf<Model>]?: PolicyValue<Actor>;\n} & {\n readonly [Relation in keyof ModelRelations<Model>]?: ContextualRelation<\n ModelRelations<Model>[Relation],\n Actor,\n Dynamic\n >;\n} & (\"actor\" extends ScalarsOf<Model> | RelationsOf<Model>\n ? unknown\n : {\n readonly actor?: {\n readonly [Path in ActorPaths<InferOutput<Actor>>]?: unknown;\n };\n }) & {\n readonly AND?:\n | ContextualRule<Model, Actor, Dynamic>\n | readonly ContextualRule<Model, Actor, Dynamic>[];\n readonly OR?: readonly ContextualRule<Model, Actor, Dynamic>[];\n readonly NOT?:\n | ContextualRule<Model, Actor, Dynamic>\n | readonly ContextualRule<Model, Actor, Dynamic>[];\n };\n\ntype ContextualRule<Model, Actor, Dynamic extends boolean = true> =\n | boolean\n | ContextualWhere<Model, Actor, Dynamic>\n | (Dynamic extends true\n ? (\n action: string,\n model: PolicyModel\n ) => ContextualRule<Model, Actor, Dynamic>\n : never);\n\n/** Complete only the edited prefix, without enumerating action permutations. */\ntype GroupSuggestions<\n Key extends string,\n Actions extends string,\n> = Key extends `${infer Head},${infer Tail}`\n ? Tail extends `${string},${string}`\n ? `${Head},${GroupSuggestions<Tail, Exclude<Actions, Trim<Head>>>}`\n : `${Head},${Tail extends ` ${string}` ? \" \" : \"\"}${Exclude<Actions, Trim<Head>>}`\n : never;\ntype SuggestedRules<M> =\n | Crud\n | ActionsOf<M>\n | GroupSuggestions<RuleKeys<M>, ActionsOf<M>>;\n\ntype ContextualPolicy<\n C extends VibORMConfig,\n Actor,\n Config extends PermissionsConfig,\n> = string extends keyof C[\"schema\"]\n ? unknown\n : {\n readonly actor: Actor;\n readonly models: {\n readonly [Model in keyof ClientSchema<C>]?: {\n readonly [Key in Reserved]?: Key extends \"mandatory\"\n ? ContextualWhere<ClientSchema<C>[Model], Actor, false>\n : ModelPolicy[Key];\n } & {\n readonly [Action in SuggestedRules<\n Model extends keyof Config[\"models\"]\n ? Config[\"models\"][Model]\n : never\n >]?: ContextualRule<ClientSchema<C>[Model], Actor>;\n } & {\n readonly [Action: string]:\n | ContextualRule<ClientSchema<C>[Model], Actor>\n | undefined;\n };\n };\n };\n\n/**\n * The policy as one extension: `client.$extends(permissions({ actor, models\n * }))`. Model names are inferred from keys independently of callback bodies,\n * so schema admission does not force a context-sensitive Config to its broad\n * constraint; the receiving `$extends` supplies the client before the inline\n * declaration is contextualized. Applied, every model of the client is\n * governed, and every call needs an actor: `db.$as(actor)`.\n */\nexport function permissions<\n T extends AnyTarget,\n const Actor extends object,\n const ModelNames extends string,\n const Config extends PermissionsConfig,\n>(\n config: Config & {\n readonly actor: Actor;\n readonly models: Record<ModelNames, unknown>;\n } & ContextualPolicy<NoInfer<T[\"config\"]>, NoInfer<Actor>, NoInfer<Config>> &\n DeclarationCheck<Config> &\n SchemaCheck<\n NoInfer<T[\"config\"][\"schema\"]>,\n Pick<Config[\"models\"], ModelNames>\n >\n): Policy<Config> & Extension<T, PermissionsFacts<T, Config>>;\nexport function permissions<const Config extends PermissionsConfig>(\n config: Config & DeclarationCheck<Config>\n): unknown {\n const actor = actorContract(config.actor);\n const compile = (schema: Schema) => compilePolicy(config, schema, actor);\n const { modes, scopes } = policyArguments(config);\n /** A bound argument: a read that carries it is never cached, but under `cache: \"allow\"`. */\n const held = (schema: Parameters<typeof bound>[0]) => {\n const value = bound(schema).required();\n return config.cache === \"allow\" ? value : value.volatile();\n };\n /**\n * What applying the policy to one schema made: what the declaration\n * names, checked once, and what a root call may reach. Each model\n * compiles the first time a call needs it, into one state every client of\n * the schema shares; a rule's own refusal comes at its model's first call.\n * Made by the first rule part, which the extension runs once per schema,\n * and again for a schema object that gained or swapped a model: a model\n * the policy lacks would be left open (R9).\n */\n const applied = new WeakMap<Schema, PolicyCompiler>();\n const governed = extension(\n NAME,\n // Every model of the schema, each read when a call first needs it.\n rule<Untyped, (schema: Schema) => object>((schema) => {\n const compiler = policyCompiler(config, { ...schema }, actor);\n applied.set(schema, compiler);\n return Object.fromEntries(\n Object.keys(compiler.declared).map((name) => [\n name,\n lazy(() => compiler.model(name).entry),\n ])\n );\n }),\n // The tenant the policy's own whole-table sets stay in (`tenant`).\n rule<Untyped, (schema: Schema) => object>((schema) =>\n Object.fromEntries(\n // The first rule part, declared before this one, applied the policy.\n Object.entries(applied.get(schema)!.declared).flatMap(\n ([name, model]) =>\n model.bound === undefined\n ? []\n : [[name, { confine: within(model.bound) }]]\n )\n )\n ),\n args({\n actor: held(actor.schema),\n scopes: held(scopeSchema(scopes)),\n [MODE]: oneOf(...modes)\n .default(DEFAULT_MODE)\n .on(selecting),\n }),\n // R9, D3: a call the policy cannot reach is refused before its\n // arguments are validated.\n call((c) => {\n // target(models) selects model calls only: each names its model.\n const model = c.model!;\n const at = applied.get(c.schema)?.declared[model];\n const kind = actionOf(c.operation);\n const mode: unknown = c.values[MODE];\n if (\n !(\n at &&\n Object.hasOwn(config.models, model) &&\n (c.operation === \"upsert\" ||\n (kind === \"create\"\n ? at.modes.includes(kind)\n : at[kind] !== undefined))\n ) ||\n (typeof mode === \"string\" &&\n mode !== DEFAULT_MODE &&\n !at.modes.includes(mode))\n )\n throw new ForbiddenError(model, c.operation);\n }, target(everyOperation)),\n methods(\n (scope: {\n $bind(values: Readonly<Record<string, unknown>>): unknown;\n }) => ({\n $as: (bound: unknown, scopes?: readonly string[]) =>\n scope.$bind({ actor: bound, scopes }),\n })\n )\n );\n return Object.freeze({ ...governed, config, compile });\n}\n"],"mappings":"4kBA6BA,MAAM,EAAW,IAAI,IAAI,CAAC,WAAY,WAAY,UAAU,CAAC,CAE7D,SAAgB,OACd,EACA,EACA,EACO,CACP,MAAM,IAAI,EAA0B,uBAAuB,IAAW,CACpE,KAAM,CAAE,UAAW,qBAAsB,GAAI,GAAS,CAAE,QAAO,CAAG,CAClE,GAAI,IAAU,IAAA,IAAa,CACzB,MACE,aAAiB,MACb,EACI,MAAM,gCAAiC,CAAE,QAAO,CAAC,CAC5D,CACF,CAAC,CAIJ,SAAS,KAAK,EAAgB,EAAmB,CAC/C,IAAI,EAAS,EACb,OAAS,CAEP,GAAM,CAAE,KAAA,EAAM,WAAY,EAC1B,GAAIA,IA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AO,GAAS,UACf,IAAS,GACT,CAAC,EAAG,MAAM,SAAS,EAAK,CAE1B,MAAM,IAAI,EAAe,EAAO,EAAE,UAAU,EAC7C,EAAOC,EAAe,CAAC,CAC1B,EACG,IAEM,CACL,KAAM,EAAgB,IACpB,EAAM,MAAM,CAAE,MAAOC,EAAO,OAAA,EAAQ,CAAC,CACxC,EACF,CACF,CACD,OAAO,OAAO,OAAO,CAAE,GAAG,EAAU,SAAQ,QAAS,CAAC"}
1
+ {"version":3,"file":"permissions.mjs","names":["type","memo","value","key","path","relation","models","bound","facts","rule","scope","target","row","left","right","known","summaries","names","written","P","walk","name","everyOperation","bound"],"sources":["../src/permissions/actor.ts","../src/permissions/rules.ts","../src/permissions/compile.ts","../src/permissions/index.ts"],"sourcesContent":["// The actor contract of viborm/permissions (plan §4.2 K2(e)): who calls is a\n// `viborm/validation` object schema, and every path a policy reads of it is one\n// of its entries. The schema is walked once, at `permissions()`, into the finite tree\n// of its paths; a path the tree does not hold is refused where the policy is\n// compiled, so a misspelt guard can never fold false at every call.\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { ClientInitializationError } from \"../errors\";\nimport type { VibSchema } from \"../validation\";\nimport { v } from \"../validation/primitives/v\";\n\n/** The paths below one actor value: named keys, or any key of a record. */\ninterface Paths {\n readonly keys?: ReadonlyMap<string, Paths>;\n readonly any?: Paths;\n readonly item?: Paths;\n}\n\n/** The members of a validation schema the walk reads. */\ninterface Walked {\n readonly type?: string;\n readonly entries?: Readonly<Record<string, unknown>>;\n readonly options?: NonNullable<Parameters<typeof v.object>[1]>;\n readonly wrapped?: unknown;\n readonly value?: unknown;\n readonly item?: unknown;\n}\n\n/** Schemas a path passes through without naming a key. */\nconst WRAPPERS = new Set([\"optional\", \"nullable\", \"lazyRef\"]);\n\nexport function refuse(\n message: string,\n model?: string,\n cause?: unknown\n): never {\n throw new ClientInitializationError(`viborm/permissions: ${message}`, {\n meta: { extension: \"viborm.permissions\", ...(model && { model }) },\n ...(cause !== undefined && {\n cause:\n cause instanceof Error\n ? cause\n : new Error(\"A non-Error value was thrown.\", { cause }),\n }),\n });\n}\n\n/** bindingSchema already resolved thunks and refused cycles. */\nfunction walk(input: unknown, at: string): Paths {\n let schema = input;\n for (;;) {\n // A viborm/validation schema, read for its kind and what it wraps.\n const { type, wrapped } = schema as Walked;\n if (type === undefined || !WRAPPERS.has(type)) break;\n schema = wrapped;\n }\n // The same schema, unwrapped, read for its children.\n const { type, entries, options, value, item } = schema as Walked;\n if (type !== \"object\" && type !== \"record\" && type !== \"array\") return {};\n let paths: Paths;\n if (type === \"array\") paths = { item: walk(item, `${at}[]`) };\n else if (type === \"record\") paths = { any: walk(value, `${at}.*`) };\n else {\n if (options?.strict === false)\n refuse(\n `the actor schema admits unknown keys at \"${at}\": a path it does not declare would be read`\n );\n paths = {\n keys: new Map(\n Object.entries(entries!)\n .filter(([key]) => !options?.omit?.includes(key))\n .map(([key, entry]) => [\n key,\n walk(entry, at === \"actor\" ? key : `${at}.${key}`),\n ])\n ),\n };\n }\n return options?.array ? { item: paths } : paths;\n}\n\n/** One actor declaration's path vocabulary and binding boundary. */\nexport interface ActorContract {\n readonly hasPath: (path: string) => boolean;\n readonly schema: StandardSchemaV1;\n}\n\n/** Whether a normalized schema takes `undefined`: published, or the literal itself. */\nconst acceptsUndefined = (value: VibSchema): boolean => {\n // A schema that takes `undefined` publishes it; any other has neither key.\n const shape = value as VibSchema & {\n acceptsUndefined?: boolean;\n value?: unknown;\n };\n return (\n shape.acceptsUndefined === true ||\n (shape.type === \"literal\" && shape.value === undefined)\n );\n};\n\n/** Normalize structural actor objects once; native validation owns parsing. */\nfunction bindingSchema(\n input: unknown,\n memo = new WeakMap<object, VibSchema>(),\n open = new Set<object>(),\n at = \"actor\"\n): VibSchema {\n // A viborm/validation schema, or a thunk of one, read structurally: what\n // is not one is refused below by its kind.\n const schema = (typeof input === \"function\" ? input() : input) as VibSchema &\n Walked & {\n readonly key?: VibSchema<string, string>;\n readonly default?: unknown;\n readonly schema?: unknown;\n readonly actions?: readonly {\n readonly type: \"transform\";\n readonly transform: (value: unknown) => unknown;\n }[];\n };\n const held = memo.get(schema);\n if (held !== undefined) return held;\n if (open.has(schema))\n refuse(\n `the actor schema is recursive at \"${at}\": its paths are not finite`\n );\n open.add(schema);\n const child = (value: unknown, path = at) =>\n bindingSchema(value, memo, open, path);\n const { type } = schema;\n let result: VibSchema = schema;\n if (type === \"object\") {\n const { transform, refuse: refusal, ...options } = schema.options ?? {};\n const sparse = options.partial !== false && options.atLeast === undefined;\n // Native required-object parsing is dense. Keep the original sparse\n // shape at the user callbacks and output boundary: absent optionals must\n // not become undefined-valued properties (including in cache identities).\n const prune = (value: unknown): Record<string, unknown> => {\n // The native parser owns this fresh object; preserve its identity for\n // refuse, transform and the result, without touching caller input.\n const parsed = value as Record<string, unknown>;\n for (const key of Object.keys(parsed))\n if (parsed[key] === undefined) delete parsed[key];\n return parsed;\n };\n result = v.object(\n Object.fromEntries(\n Object.entries(schema.entries!).map(([key, value]) => [\n key,\n child(value, at === \"actor\" ? key : `${at}.${key}`),\n ])\n ),\n {\n ...options,\n partial: false,\n refuse: sparse && refusal ? (value) => refusal(prune(value)) : refusal,\n transform: sparse\n ? (value) => {\n // Refuse already saw the pruned object. Its mutations survive,\n // even if it deliberately introduced an undefined property.\n const parsed = refusal ? value : prune(value);\n return transform ? transform(parsed) : parsed;\n }\n : transform,\n }\n );\n } else if (type === \"optional\")\n result = v.optional(child(schema.wrapped), schema.default);\n else if (type === \"nullable\") result = v.nullable(child(schema.wrapped));\n else if (type === \"lazyRef\") result = child(schema.wrapped);\n else if (type === \"array\") result = v.array(child(schema.item));\n else if (type === \"record\")\n result = v.record(schema.key!, child(schema.value));\n else if (type === \"union\" && Array.isArray(schema.options))\n result = v.union(schema.options.map((member) => child(member)));\n else if (type === \"pipe\")\n result = v.pipe(child(schema.schema), ...schema.actions!);\n // These wrappers delegate undefined correctly, but their ordinary object\n // metadata does not publish it. Actor objects require this fact before\n // choosing whether to run a member's validator on a missing key.\n const delegates =\n type === \"union\"\n ? schema.options\n : type === \"pipe\"\n ? [schema.schema]\n : type === \"nullable\"\n ? [schema.wrapped]\n : [];\n if (\n result !== schema &&\n Array.isArray(delegates) &&\n delegates.some((member) => acceptsUndefined(child(member)))\n )\n Object.defineProperty(result, \"acceptsUndefined\", { value: true });\n open.delete(schema);\n memo.set(schema, result);\n return result;\n}\n\n/**\n * The one actor contract supplies both the finite policy path vocabulary and\n * the schema used at binding. Actor objects require their non-optional fields;\n * normalizing structural schemas leaves union selection, defaults, transforms\n * and array/record traversal with their existing native validators.\n */\nexport function actorContract(schema: unknown): ActorContract {\n // Any value: an object schema is told apart by its `type`.\n if ((schema as Walked | undefined)?.type !== \"object\")\n refuse(\"the actor must be a viborm/validation object schema (v.object)\");\n const normalized = bindingSchema(schema);\n const root = walk(normalized, \"actor\");\n return {\n hasPath(path) {\n let at: Paths | undefined = root;\n for (const key of path.split(\".\")) {\n at = at.keys?.get(key) ?? at.any;\n if (at === undefined) return false;\n }\n return true;\n },\n schema: normalized,\n };\n}\n\n/** Whether `T` is one of `Seen`, both ways: a structural subtype is not the same object. */\ntype IsSeen<T, Seen> = true extends (\n Seen extends unknown\n ? [T] extends [Seen]\n ? [Seen] extends [T]\n ? true\n : false\n : false\n : never\n)\n ? true\n : false;\n\n/**\n * Every dotted path of an actor value: a key, or a key and a path below it; a\n * record's keys are any string. The object types already walked stop the walk,\n * so a recursive type ends without a depth number (plan §11.2 F8).\n */\nexport type ActorPaths<T, Seen = never> = T extends readonly unknown[]\n ? never\n : T extends object\n ? IsSeen<T, Seen> extends true\n ? never\n : string extends keyof T\n ? string\n : {\n [K in keyof T & string]-?:\n | K\n | `${K}.${ActorPaths<NonNullable<T[K]>, Seen | T>}`;\n }[keyof T & string]\n : never;\n\n/**\n * The actor a binding takes: what its schema parses to, read only, where an\n * entry whose value may be `undefined` may also be left out (an optional\n * entry's output keeps its key; `v.object`'s input type makes every key\n * optional).\n */\nexport type ActorFacts<T> = T extends readonly (infer Item)[]\n ? readonly ActorFacts<Item>[]\n : T extends Date | ((...args: never[]) => unknown)\n ? T\n : T extends object\n ? {\n readonly [K in keyof T as undefined extends T[K]\n ? never\n : K]: ActorFacts<T[K]>;\n } & {\n readonly [K in keyof T as undefined extends T[K]\n ? K\n : never]?: ActorFacts<T[K]>;\n }\n : T;\n","// The schema-independent predicate language of viborm/permissions. Applications\n// name their own fields, actor paths and authorization conventions.\n\n/** A `where` over a model's relations and the actor's facts, held as data. */\nexport type Where = { readonly [key: string]: unknown };\n/** A boolean grant, a `where`, or a function of its declared action and model. */\nexport type Rule =\n | boolean\n | Where\n | ((action: string, model: PolicyModel) => Rule);\n\n/** What a rule function reads of the model it is evaluated at. */\nexport interface PolicyModel {\n readonly name: string;\n /** Its actions, in declaration order (none for a model the policy does not list). */\n readonly actions: readonly string[];\n}\n\n/** A `where` no row satisfies. Internal compiler identity, not a public helper. */\nexport const FALSE: Where = Object.freeze({ OR: Object.freeze([]) });\n","// The one formula of viborm/permissions (plan §3.2 R1), compiled once per schema:\n//\n// P(M, a) = scopes(M, a) ∧ mandatory(M) ∧ ⋁_{b ⊒ a} rule(M, b)(b)\n//\n// Rule functions are evaluated here for their declared action, and\n// the policy's spellings are lowered to the words of a rule: `{ actor: \"p\" }`\n// in a value position is `arg(\"actor\", \"p\")`, `{ actor: { p: v } }` in a filter\n// a `provided` test of it, `$if` and `$exists` their words, and a relation\n// whose value is an action name the target's predicate at that action,\n// inlined (D7). What comes out is each model's rule entry (K3): its read\n// predicate, its read-gated fields and `$access` facts (D5, D6, K5), its\n// modes, the produced row's placement, moves and acyclic relations (R4, K4),\n// and the predicate each write takes. A placement or a move drops a conjunct\n// another one, or a judgement the same statement makes, provably implies\n// (plan §11.4). The proof reads what each word it wrote stands for.\n\nimport { ClientInitializationError } from \"../errors\";\nimport { check, facts, gate, only } from \"../extensions/judge-words\";\nimport {\n arg,\n exists,\n nothing,\n now,\n provided,\n row,\n when,\n} from \"../extensions/rule-words\";\nimport type { ArgTest, VibORMConfig } from \"../index\";\nimport { type ActorContract, actorContract, refuse } from \"./actor\";\nimport { FALSE, type PolicyModel, type Rule, type Where } from \"./rules\";\n\ntype Schema = VibORMConfig[\"schema\"];\ntype AnyModel = Schema[string];\n\n/** What the compiler reads of a model's declaration. */\ninterface ModelFacts {\n readonly scalars: Readonly<\n Record<\n string,\n {\n readonly \"~\": {\n readonly state: {\n readonly type: string;\n readonly isId?: boolean;\n readonly nullable?: boolean;\n };\n };\n }\n >\n >;\n readonly relations: Readonly<\n Record<\n string,\n {\n readonly \"~\": {\n readonly state: {\n readonly foreignKey?: {\n readonly fields: readonly string[];\n readonly references: readonly string[];\n };\n };\n settleTarget(): unknown;\n };\n }\n >\n >;\n readonly compoundId?: Readonly<Record<string, { readonly entries: object }>>;\n}\n\n/** One model's declaration (plan §1.1). */\nexport interface ModelPolicy {\n readonly mandatory?: Where;\n readonly actions?: { readonly [action: string]: readonly string[] };\n readonly create?: Rule;\n readonly operations?: {\n readonly read?: string;\n readonly update?: string;\n readonly delete?: string;\n };\n readonly fields?: {\n readonly [field: string]: {\n readonly read?: string;\n readonly write?: string;\n };\n };\n readonly domains?: { readonly [name: string]: Rule };\n /** A named action or comma-separated actions' rule: `read`, `read, update`, … */\n readonly [action: string]: Rule | undefined;\n}\n\nexport interface PermissionsConfig {\n /** Who calls: a `viborm/validation` object schema of the request's facts. */\n readonly actor: object;\n readonly mandatory?: Where;\n readonly models: { readonly [model: string]: ModelPolicy };\n /**\n * `\"allow\"` lets a governed read be served from the cache (OD-10). A cached\n * answer was judged when it was stored: a revoked grant or an expired\n * session reaches it only after its TTL. Refused when absent.\n */\n readonly cache?: \"allow\";\n /**\n * The tenant a governed call stays in: on every model with a scalar\n * `field` but the ones `except` names, a set the policy's rules compute\n * over a whole table, where a positive test reads it, holds only the rows\n * whose `field` is the actor's `actor` path (`rows.confine`). Nothing else\n * reads differently. `except` names the models whose rows a rule reads\n * beyond the actor's tenant: a person's memberships of other\n * organizations, a shared catalogue.\n */\n readonly tenant?: {\n readonly field: string;\n readonly actor: string;\n readonly except?: readonly string[];\n };\n}\n\n/**\n * One model's rule entry, as `permissions` hands it to the chain: its read\n * predicate, each field it gates and its `$access` facts, the modes that\n * narrow a call's own rows (`root`), the placement every created row\n * satisfies (R4), and the predicate each write takes: an update writing a\n * protected field its own (R3), one writing a field the placement reads the\n * placement again (a move). An entry part (`read`, `update`, `delete`) whose\n * action the model does not declare takes no row. Predicates are shared by\n * identity wherever they are read.\n */\nexport interface CompiledModel {\n readonly read: {\n readonly where: object;\n readonly fields: { readonly [field: string]: Gate };\n readonly select?: { readonly [key: `$${string}`]: Facts };\n };\n readonly root?: readonly object[];\n readonly create: { readonly check: Check };\n readonly update: {\n readonly where: Only;\n readonly fields: {\n readonly [field: string]: {\n readonly where?: Only;\n readonly check?: Check;\n };\n };\n };\n readonly delete: { readonly where: Only };\n /** The self relations an update keeps acyclic: they need every model compiled. */\n readonly acyclic: () => readonly string[];\n}\ntype Gate = ReturnType<typeof gate<unknown>>;\ntype Facts = ReturnType<typeof facts<string>>;\ntype Check = ReturnType<typeof check<unknown>>;\ntype Only = ReturnType<typeof only<unknown>>;\n\nexport interface CompiledPolicy {\n /** Each admitted scope and its transitive implications, including itself. */\n readonly scopes: Readonly<Record<string, readonly string[]>>;\n /** Every model of the schema: one the policy does not list holds nothing (R9). */\n readonly models: { readonly [model: string]: CompiledModel };\n}\n\n/** The `as` value a call takes when it names none: it narrows nothing. */\nexport const DEFAULT_MODE = \"default\";\n/** The call argument that narrows a call to one action or domain (R8). */\nexport const MODE = \"as\";\n/** The projection key the entry declares on every listed model (D6, OD-2). */\nexport const EVIDENCE_KEY = \"$access\";\n/** The placement's name: the predicate of `create` (R4). */\nconst PLACE = \"$create\";\n\nconst RESERVED = new Set([\n \"mandatory\",\n \"actions\",\n \"operations\",\n \"fields\",\n \"domains\",\n]);\n/** Keys a declaration no longer takes, and what took their place. */\nconst RETIRED: Readonly<Record<string, string>> = {\n within: 'was renamed to \"mandatory\"',\n arms: \"was removed; assign rules to named actions\",\n};\nconst OPERATIONS = new Set([\"read\", \"update\", \"delete\"]);\nconst CRUD = new Set([\"create\", \"read\", \"update\", \"delete\"]);\nconst CONFIG_KEYS = new Set([\n \"actor\",\n \"mandatory\",\n \"models\",\n \"cache\",\n \"tenant\",\n]);\nconst FIELD_KEYS = new Set([\"read\", \"write\"]);\n\nconst LOGICAL = new Set([\"AND\", \"OR\", \"NOT\"]);\n/** A check of another model's rows that reads no column of the row judged. */\nconst EXISTS = \"$exists\";\n/** A row a rule reads: its model, and why a `{ $row, up }` may not cross it. */\ninterface Scope {\n readonly model: string;\n readonly sealed?: boolean;\n}\n/** `{ $row, up }` (a record of these two keys): a column of a row the rule reads, `up` bodies above. */\nconst isEnclosingRow = (\n value: Record<string, unknown>\n): value is { readonly $row: string; readonly up: number } =>\n typeof value.$row === \"string\" &&\n Number.isSafeInteger(value.up) &&\n // A safe integer, which `isSafeInteger` does not tell the types.\n (value.up as number) >= 0;\nconst QUANTIFIERS = new Set([\"is\", \"isNot\", \"some\", \"every\", \"none\"]);\n/**\n * A plain object: a clause or an operator's record, never a value (a Date, a\n * Decimal, bytes). A field reference is a plain object whose only key is a\n * symbol: read as a record it would be `{}`, true everywhere, so an object\n * with a symbol key is a value.\n */\nexport const isRecord = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return (\n (prototype === Object.prototype || prototype === null) &&\n Object.getOwnPropertySymbols(value).length === 0\n );\n};\nconst isActorField = (value: unknown): value is { actor: string } =>\n isRecord(value) &&\n typeof value.actor === \"string\" &&\n Object.keys(value).length === 1;\n\n/** A clause: a `where`, or `false` when it folds false while compiling. */\ntype Clause = Where | false;\nconst isTrue = (clause: Where) => Object.keys(clause).length === 0;\nconst membersOf = (clause: Where, key: \"AND\" | \"OR\"): Where[] =>\n Object.keys(clause).length === 1 && Array.isArray(clause[key])\n ? // A list, checked just above: `and` and `or` write lists of clauses.\n (clause[key] as Where[])\n : [clause];\n/**\n * A rule's record that writes `$if` or `$exists` beside its filters: the one\n * conjunction it was written as, which a conjunction it joins holds whole,\n * and its conjuncts in the order the rule spells them.\n */\nexport const written = new WeakMap<Where, readonly Where[]>();\n\nfunction and(clauses: readonly Clause[]): Clause {\n if (clauses.includes(false)) return false;\n // No clause is `false`: that returned above.\n const kept = (clauses as Where[])\n .filter((clause) => !isTrue(clause))\n .flatMap((clause) =>\n written.has(clause) ? [clause] : membersOf(clause, \"AND\")\n );\n if (kept.length < 2) return kept[0] ?? {};\n return { AND: kept };\n}\n\n/** `cache`'s value at `key`, built once; a build that throws is asked again. */\nconst memo = <K, V>(\n cache: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n build: () => V\n): V => {\n let value = cache.get(key);\n if (value === undefined) cache.set(key, (value = build()));\n return value;\n};\n\n/**\n * What a word the compiler writes stands for, as its proof reads it: an\n * argument's value (its argument and path), a condition on one (the value\n * and its test), another model's rows (the model and the `where` they\n * match), a column of an enclosing row (its column and how many bodies up).\n */\ntype Made =\n | { readonly arg: readonly [control: string, path: unknown] }\n | { readonly provided: readonly [tested: object, test: Where] }\n | { readonly exists: readonly [model: string, body: Where] }\n | { readonly row: readonly [column: string, up: unknown] };\n\n/** A model's admitted action graph, rule assignments and projection meaning. */\ninterface ActionRules {\n readonly rules: ReadonlyMap<\n string,\n { readonly rule: Rule | undefined; readonly source: string }\n >;\n readonly closure: ReadonlyMap<string, readonly string[]>;\n}\n\n/** Resolve grouped rule keys once, before any consumer reads their actions. */\nfunction actionsOf(name: string, policy: ModelPolicy): ActionRules {\n const implies = new Map<string, readonly string[]>(\n Object.entries(policy.actions ?? {})\n );\n const rules = new Map<\n string,\n { readonly rule: Rule | undefined; readonly source: string }\n >();\n // Never reinterpret a key of the declaration, nor an old restriction or\n // grant container, as an action.\n const notAction = (key: string, at: string) => {\n if (Object.hasOwn(RETIRED, key))\n refuse(`${at}: \"${key}\" ${RETIRED[key]}`, name);\n if (RESERVED.has(key))\n refuse(\n `${at}: \"${key}\" is a key of the declaration, not an action`,\n name\n );\n };\n // Only a model's rule keys can group actions. Graph edges name individual\n // actions, so accepting a comma there would create another action.\n for (const action of [...implies.keys(), ...[...implies.values()].flat()])\n if (action.includes(\",\"))\n refuse(\n `models.${name}: \"${action}\" is not an individual action; commas group rules only`,\n name\n );\n\n for (const sourceKey of Object.keys(policy)) {\n if (RESERVED.has(sourceKey)) continue;\n const source = `models.${name}.${sourceKey}`;\n const binding = { rule: policy[sourceKey], source };\n const keys = sourceKey.includes(\",\")\n ? sourceKey\n .split(\",\")\n .map((key) => key.replace(/^[ \\t\\r\\n]+|[ \\t\\r\\n]+$/g, \"\"))\n : [sourceKey];\n for (const key of keys) {\n if (key.length === 0)\n refuse(\n `${source}: an action group cannot contain an empty member`,\n name\n );\n notAction(key, source);\n const previous = rules.get(key);\n if (previous !== undefined)\n refuse(\n `${source}: action \"${key}\" already has a rule at ${previous.source}`,\n name\n );\n rules.set(key, binding);\n if (implies.has(key)) continue;\n // An explicit graph lists every action: unknown members would introduce an undeclared permission.\n if (policy.actions)\n refuse(\n `${source}: neither an action ${name} lists in \\`actions\\` nor a key of the declaration (${[...RESERVED].join(\", \")}); unknown action \"${key}\"`,\n name\n );\n // Without a graph a model's actions are CRUD: any other key is a typo\n // or a custom action, and was never to become a permission unlisted.\n if (!CRUD.has(key))\n refuse(\n `${source}: \"${key}\" is not create, read, update or delete. A custom action is declared in the model's graph (one outside a graph was removed): actions: { read: [], ${key}: [\"read\"] }`,\n name\n );\n implies.set(key, []);\n }\n }\n // An update or a delete grants read by default: whoever may change a row\n // may see it. A create is a placement over a proposed row and implies\n // nothing; custom actions imply only what is declared.\n for (const action of [\"update\", \"delete\"]) {\n const inherited = implies.get(action);\n if (inherited === undefined) continue;\n if (!implies.has(\"read\")) implies.set(\"read\", []);\n if (!inherited.includes(\"read\"))\n implies.set(action, [...inherited, \"read\"]);\n }\n for (const [action, implied] of implies) {\n notAction(action, `models.${name}`);\n for (const next of implied)\n if (!implies.has(next))\n refuse(\n `models.${name}.actions.${action} implies \"${next}\", which ${name} does not declare`,\n name\n );\n }\n // Each action and what it implies, depth first.\n const reach = (action: string, reached: Set<string>): Set<string> => {\n if (!reached.has(action)) {\n reached.add(action);\n for (const next of implies.get(action)!) reach(next, reached);\n }\n return reached;\n };\n return {\n rules,\n closure: new Map(\n [...implies.keys()].map((action) => [\n action,\n [...reach(action, new Set())],\n ])\n ),\n };\n}\n\n/**\n * What a policy's arguments accept, read from the declaration alone: every\n * `as` value (the default, each listed model's actions and domains) and\n * each credential scope with the scopes it implies. A declaration the\n * compiler refuses yields the default alone: applying it refuses it there.\n */\nexport function policyArguments(config: PermissionsConfig): {\n readonly modes: readonly string[];\n readonly scopes: Readonly<Record<string, readonly string[]>>;\n} {\n try {\n const modes = new Set<string>([DEFAULT_MODE]);\n const scopes: Record<string, readonly string[]> = {};\n for (const [name, policy] of Object.entries(config.models)) {\n const { closure } = actionsOf(name, policy);\n for (const [action, implied] of closure) {\n modes.add(action);\n scopes[`${name}.${action}`] = implied.map((next) => `${name}.${next}`);\n }\n for (const domain of Object.keys(policy.domains ?? {})) modes.add(domain);\n }\n return { modes: [...modes], scopes };\n } catch {\n return { modes: [DEFAULT_MODE], scopes: {} };\n }\n}\n\n/** `{ control, path? }`: an argument's value, as a rule may spell one. */\nconst isReference = (\n value: Record<string, unknown>\n): value is { readonly control: string; readonly path?: unknown } =>\n typeof value.control === \"string\" &&\n Object.keys(value).every((key) => key === \"control\" || key === \"path\");\n\n/**\n * Compiles a policy against the schema it governs, every model at once: what\n * `policy.compile(schema)` shows.\n */\nexport function compilePolicy(\n config: PermissionsConfig,\n schema: Schema,\n actor: ActorContract = actorContract(config.actor)\n): CompiledPolicy {\n const compiler = policyCompiler(config, schema, actor);\n return {\n scopes: policyArguments(config).scopes,\n models: Object.fromEntries(\n Object.keys(schema).map((name) => [name, compiler.model(name).entry])\n ),\n };\n}\n\n/**\n * A model's action per entry part and its `as` modes: what applying a policy\n * needs before any query.\n */\ninterface DeclaredModel {\n readonly read?: string;\n readonly update?: string;\n readonly delete?: string;\n /** Its actions, then its domains: each names the predicate of its own name. */\n readonly modes: readonly string[];\n /** What the policy's own whole-table sets of this model hold (`tenant`). */\n readonly bound?: Where | undefined;\n}\n\n/** What a model declares, read without lowering a rule. */\ninterface Declared extends DeclaredModel {\n /**\n * Field → the predicate an update writing it takes (by name): `update`'s,\n * or `$write:<field>` where its write action is another.\n */\n readonly writes: { readonly [field: string]: string };\n readonly reads: { readonly [field: string]: string };\n /** Field → its move (filled when the model compiles). */\n readonly moves?: { readonly [field: string]: string };\n}\n/** A model the policy does not list declares nothing. */\nconst UNLISTED: Declared = {\n modes: [],\n writes: {},\n reads: {},\n};\n\n/**\n * One policy against one schema, compiled a model at a time. Building it\n * checks everything the declaration says without lowering a rule (its keys,\n * models, action graphs, operations, fields and `as` names), so those\n * refusals come when the policy is applied; a rule's own refusals (a field,\n * an actor path, a relation's action, a rule that reads itself) come when\n * its model is first compiled. Models compile into one shared state, so each\n * predicate is lowered once whatever order they are asked in, and the output\n * is the same as compiling every model at once.\n */\nexport interface PolicyCompiler {\n /** Every model of the schema: its parts' actions and modes. */\n readonly declared: { readonly [model: string]: DeclaredModel };\n /** One model compiled: one the policy does not list holds nothing (R9). */\n model(name: string): Compiled;\n}\n\nconst NO_RELATIONS: readonly string[] = [];\n/** One model compiled: its predicates by name, which `acyclic` walks, and its entry. */\nexport interface Compiled {\n readonly predicates: ReadonlyMap<string, Where>;\n readonly entry: CompiledModel;\n}\n\nexport function policyCompiler(\n config: PermissionsConfig,\n schema: Schema,\n actor: ActorContract = actorContract(config.actor)\n): PolicyCompiler {\n const made = new WeakMap<object, Made>();\n /**\n * One compilation's structural keys: two values share a key exactly when they\n * are the same value, numbers by `Object.is` (NaN and ±Infinity are no\n * `null`), bigints, valid dates by their instant, arrays and records member by\n * member; anything else by identity. A record or an array is keyed once, so\n * equality, duplicate removal and the implication cache cost one lookup\n * however often a shared clause is met. Keys hold only for one compilation,\n * which never mutates what it reads.\n */\n const shapes = new Map<string, string>();\n const known = new WeakMap<object, string>();\n // Opaque values (a Decimal, bytes, a symbol) are equal only to themselves.\n const opaque = new Map<unknown, string>();\n let next = 0;\n const keyOf = (value: unknown): string => {\n if (typeof value === \"number\")\n return Object.is(value, -0) ? \"n-0\" : `n${value}`;\n if (typeof value === \"string\") return `s${JSON.stringify(value)}`;\n if (typeof value === \"bigint\") return `b${value}`;\n if (value == null || typeof value === \"boolean\") return `p${value}`;\n // A date is read at each comparison; an invalid one equals only itself.\n if (value instanceof Date && !Number.isNaN(value.getTime()))\n return `d${value.getTime()}`;\n if (typeof value !== \"object\") {\n let key = opaque.get(value);\n if (key === undefined) opaque.set(value, (key = `o${next++}`));\n return key;\n }\n let key = known.get(value);\n if (key !== undefined) return key;\n // A word is what it stands for; another value equals only itself.\n const word = made.get(value);\n if (word !== undefined) key = `w${keyOf(word)}`;\n else if (Array.isArray(value) || isRecord(value)) {\n const shape = Array.isArray(value)\n ? `[${value.map(keyOf).join(\",\")}]`\n : `{${Object.keys(value)\n .sort()\n .map((field) => `${JSON.stringify(field)}:${keyOf(value[field])}`)\n .join(\",\")}}`;\n key = shapes.get(shape);\n if (key === undefined) shapes.set(shape, (key = `#${next++}`));\n } else key = `o${next++}`;\n known.set(value, key);\n return key;\n };\n const same = (x: unknown, y: unknown): boolean =>\n (x === y && typeof x !== \"number\") || keyOf(x) === keyOf(y);\n /** `members` without a repeated value, in order. */\n const distinct = <T>(members: readonly T[]): T[] => {\n const seen = new Set<string>();\n return members.filter((member) => {\n const key = keyOf(member);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n };\n const or = (clauses: readonly Clause[]): Clause => {\n const kept = clauses.filter((clause): clause is Where => clause !== false);\n if (kept.length === 0) return false;\n if (kept.some(isTrue)) return {};\n // Rules have already been evaluated at their declaring actions. Equal\n // resulting branches contribute once without suppressing callback evaluation.\n const flat = distinct(kept.flatMap((member) => membersOf(member, \"OR\")));\n return flat.length === 1 ? flat[0]! : { OR: flat };\n };\n /** What `word` stands for, kept for the proof. */\n const wrote = (word: object, stands: Made): Where => {\n made.set(word, stands);\n // A word stands where a filter or a value goes: the rule's admission\n // reads it in that place, its members hidden from every type.\n return word as Where;\n };\n const madeOf = (value: unknown): Made | undefined =>\n typeof value === \"object\" && value !== null ? made.get(value) : undefined;\n /** A filter: a `where`, or a word that stands for one. */\n const isClause = (value: unknown): value is Where =>\n isRecord(value) || madeOf(value) !== undefined;\n /** An argument's value: the actor's, or the call's scopes. */\n const ref = (control: string, path?: unknown) =>\n // The rule's admission refuses a path that is not a string.\n wrote(arg(control, path as string | undefined), {\n arg: [control, path],\n });\n /** True only where the argument's value passes the test. */\n const condition = (control: string, path: unknown, test: Where) => {\n // The rule's admission refuses a path that is not a string.\n const tested = arg(control, path as string | undefined);\n // The rule's admission checks the test and refuses another shape.\n return wrote(provided(tested, test as ArgTest), {\n provided: [wrote(tested, { arg: [control, path] }), test],\n });\n };\n for (const key of Object.keys(config))\n if (!CONFIG_KEYS.has(key))\n refuse(\n key === \"levels\"\n ? 'levels was removed: declare the graph on each model instead, actions: { read: [], update: [\"read\"], full: [\"update\"] }'\n : `\"${key}\" is not a key of the policy (${[...CONFIG_KEYS].join(\", \")})`\n );\n for (const name of Object.keys(config.models))\n if (!Object.hasOwn(schema, name))\n refuse(`models.${name}: the schema has no such model`, name);\n\n const names = new Map<AnyModel, string>(\n Object.entries(schema).map(([name, model]) => [model, name])\n );\n const stateOf = (name: string) =>\n // What compiling reads of a model's state: a narrower view of it.\n schema[name]![\"~\"].state as unknown as ModelFacts;\n const relationOf = (name: string, relation: string) =>\n Object.hasOwn(stateOf(name).relations, relation)\n ? stateOf(name).relations[relation]![\"~\"]\n : undefined;\n const targetOf = (name: string, relation: string) => {\n const settled = relationOf(name, relation)?.settleTarget();\n // A relation settles to a model of the schema, or none, which has no name.\n return names.get(settled as AnyModel);\n };\n\n const actions = new Map<string, ActionRules>(\n Object.entries(config.models).map(([name, policy]) => [\n name,\n actionsOf(name, policy),\n ])\n );\n const models = new Map<string, PolicyModel>();\n const modelOf = (name: string): PolicyModel =>\n memo(models, name, () =>\n Object.freeze({\n name,\n actions: Object.freeze([...(actions.get(name)?.closure.keys() ?? [])]),\n })\n );\n\n // The declared rule owns callback evaluation. Inheritance reuses that exact\n // predicate; credential scope gates apply only to the requested action.\n const rules = new Map<string, Clause>();\n const predicates = new Map<string, Clause>();\n /** Every `P(M, a)`: inlined anywhere, its `{ $row, up }` never leaves it. */\n const inlined = new WeakSet<Where>();\n const open: string[] = [];\n const scope = (name: string, action: string): Where => ({\n OR: [\n condition(\"scopes\", \"unrestricted\", { equals: true }),\n condition(\"scopes\", \"allowed\", { has: `${name}.${action}` }),\n ],\n });\n const ruleAt = (name: string, action: string): Clause =>\n memo(rules, `${name}.${action}`, () => {\n const binding = actions.get(name)!.rules.get(action);\n return binding?.rule === undefined\n ? false\n : lower(name, action, binding.rule, binding.source);\n });\n const restrictions = new Map<string, Clause>();\n // Lowered at no action: a callback in it is refused where it stands.\n const restriction = (name: string): Clause =>\n memo(restrictions, name, () =>\n and([\n lower(\n name,\n undefined,\n config.models[name]!.mandatory ?? {},\n `models.${name}.mandatory`\n ),\n lower(name, undefined, config.mandatory ?? {}, \"mandatory\"),\n ])\n );\n const P = (name: string, action: string): Clause => {\n const key = `${name}.${action}`;\n return memo(predicates, key, () => {\n if (open.includes(key))\n refuse(\n `models.${key} reads itself: ${[...open.slice(open.indexOf(key)), key].join(\" → \")}`,\n name\n );\n open.push(key);\n // A compiler outlives a refusal (a model compiles at its first call, and\n // the next call asks again): the walk is unwound whatever happens.\n try {\n const declared = actions.get(name)!;\n const inherited =\n declared.rules.get(action)?.rule === false\n ? []\n : [...declared.closure].flatMap(([from, reaches]) =>\n reaches.includes(action) ? [from] : []\n );\n const branches = inherited.map((from) => ruleAt(name, from));\n const granted = or(branches);\n const clause = and([restriction(name), absorb(name, granted)]);\n if (clause !== false) inlined.add(clause);\n return clause;\n } finally {\n open.pop();\n }\n });\n };\n /**\n * A disjunction without a member another member provably contains: where\n * `x ⇒ y`, `x ∨ y` is `y`, so `x` is dropped (the later of two equivalent\n * members). Rules evaluated at their declared action and inherited (a\n * grouped `\"read, update\": capped(rule)`) differ per action only by what\n * the higher action narrows (`role in [...]`, a coverage list), so the\n * narrower branches fold into the widest one, as the plan's one-branch\n * form had them, with the same rows. Sound, never complete (§11.4 D13):\n * what the prover cannot show stays.\n */\n const absorb = (name: string, clause: Clause): Clause => {\n if (clause === false || !Array.isArray(clause.OR)) return clause;\n // lower/or normalize siblings into AND, so OR is the only root key here.\n const members = clause.OR as Where[];\n const kept = prune(\n name,\n members,\n [...members.keys()],\n (at, dropped) =>\n members.some(\n (wider, other) =>\n other !== at &&\n !dropped.has(other) &&\n implies(name, members[at]!, wider) &&\n // Equivalent members keep the earlier one.\n !(other > at && implies(name, wider, members[at]!))\n ),\n (remaining) => and([restriction(name), or(remaining)])\n );\n return kept.length === 1 ? kept[0]! : { OR: kept };\n };\n\n /** A path the actor schema declares, or the refusal naming where it is read. */\n const path = (at: string, read: unknown) => {\n if (typeof read === \"string\" && !actor.hasPath(read))\n refuse(\n `${at} reads actor path \"${read}\", which the actor schema does not declare`\n );\n };\n /** Each model's tenant bound (`tenant`), checked once: undefined where the model has no such field. */\n const tenantOf = (\n tenant: PermissionsConfig[\"tenant\"]\n ): ((name: string) => Where | undefined) => {\n if (tenant === undefined) return () => undefined;\n const except = tenant?.except ?? [];\n if (\n !isRecord(tenant) ||\n typeof tenant.field !== \"string\" ||\n typeof tenant.actor !== \"string\" ||\n !Array.isArray(except) ||\n except.some((name) => typeof name !== \"string\") ||\n Object.keys(tenant).some(\n (key) => ![\"field\", \"actor\", \"except\"].includes(key)\n )\n )\n refuse(\n \"tenant is { field, actor, except? }: the scalar field that names a row's tenant, the actor path that names the caller's, and the models read beyond it\"\n );\n path(\"tenant.actor\", tenant.actor);\n const holds = (name: string) =>\n Object.hasOwn(stateOf(name).scalars, tenant.field);\n if (!Object.keys(schema).some(holds))\n refuse(\n `tenant.field: no model of the schema has a scalar field \"${tenant.field}\"`\n );\n for (const name of except)\n if (!(Object.hasOwn(schema, name) && holds(name)))\n refuse(\n `tenant.except names ${name}, which is not a model of the schema with a scalar field \"${tenant.field}\"`\n );\n const bound: Where = { [tenant.field]: ref(\"actor\", tenant.actor) };\n return (name) =>\n holds(name) && !except.includes(name) ? bound : undefined;\n };\n /**\n * A value position: the actor's fields and the other spellings of a value\n * as their words, checked. A document compared whole (a JSON value) is a\n * literal: an actor value is the operand itself, never an object inside it.\n */\n const value = (\n at: string,\n input: unknown,\n enclosing: (row: { readonly $row: string; readonly up: number }) => void,\n spelled = true\n ): unknown => {\n // A list's members keep `{ actor }` as written and check no path.\n if (Array.isArray(input))\n return input.map((item) => value(at, item, enclosing, false));\n if (spelled && isActorField(input)) {\n path(at, input.actor);\n return ref(\"actor\", input.actor);\n }\n if (!isRecord(input)) return input;\n if (spelled && input.control === \"actor\") path(at, input.path);\n if (isReference(input)) return ref(input.control, input.path);\n const keys = Object.keys(input);\n if (typeof input.$row === \"string\" && keys.length === 2) {\n // `up` counts bodies: another value would read the rule's own row.\n if (!isEnclosingRow(input))\n refuse(\n `${at}: { $row, up } takes a column and a whole number, 0 or more`\n );\n enclosing(input);\n // `up` was checked to be a whole number above.\n return wrote(row(input.$row, input.up as number), {\n row: [input.$row, input.up],\n });\n }\n if (input.now === true && keys.length === 1) return now;\n return Object.fromEntries(\n keys.map((key) => [\n key,\n key === \"equals\" &&\n isRecord(input[key]) &&\n !isReference(input[key]) &&\n !isActorField(input[key])\n ? input[key]\n : value(at, input[key], enclosing, spelled),\n ])\n );\n };\n /** `{ actor: { p: v } }` in a filter: one condition per leaf. */\n const conditions = (at: string, facts: unknown, prefix = \"\"): Where[] => {\n if (!isRecord(facts))\n refuse(\n `${at} tests the actor with a value that is not an object of its facts`\n );\n // An empty object tests nothing: it would hold for every actor.\n if (Object.keys(facts).length === 0)\n refuse(\n `${at} tests the actor${prefix ? ` at \"${prefix.slice(0, -1)}\"` : \"\"} with an empty object`\n );\n return Object.entries(facts).flatMap(([key, fact]) => {\n const read = `${prefix}${key}`;\n if (isRecord(fact)) return conditions(at, fact, `${read}.`);\n path(at, read);\n if (fact !== null && typeof fact === \"object\")\n refuse(\n `${at} tests actor path \"${read}\" against ${Array.isArray(fact) ? \"a list\" : \"a value that is not a literal\"}`\n );\n return [\n condition(\n \"actor\",\n read,\n fact === null ? { exists: false } : { equals: fact }\n ),\n ];\n });\n };\n\n /** A rule of `name` read at `action` (written at `at`), lowered to the `where` vocabulary. */\n const lower = (\n name: string,\n action: string | undefined,\n rule: unknown,\n at: string,\n scopes: readonly Scope[] = [{ model: name }]\n ): Clause => {\n if (typeof rule === \"boolean\") return rule ? {} : false;\n if (typeof rule === \"function\") {\n if (action === undefined)\n refuse(\n `${at}: mandatory is action-independent and cannot contain callbacks`,\n name\n );\n // Whatever a rule function throws is its model's refusal, like any\n // other mistake in a rule: it fails that model, never another.\n let evaluated: unknown;\n try {\n evaluated = rule(action, modelOf(name));\n } catch (error) {\n if (error instanceof ClientInitializationError) throw error;\n refuse(`${at}: the rule function threw at \"${action}\"`, name, error);\n }\n return lower(name, action, evaluated, at, scopes);\n }\n if (!isRecord(rule))\n refuse(\n `${at}: a rule is a boolean, a where object or a function of the action`,\n name\n );\n const state = stateOf(name);\n const out: Record<string, unknown> = {};\n const also: Clause[] = [];\n let tested: Where | undefined;\n let existing: Where | undefined;\n for (const [key, member] of Object.entries(rule)) {\n if (LOGICAL.has(key)) {\n const list = (Array.isArray(member) ? member : [member]).map((item) =>\n lower(name, action, item, at, scopes)\n );\n const folded =\n key === \"OR\"\n ? or(list)\n : and(\n key === \"AND\"\n ? list\n : list.map((item) =>\n item === false ? {} : isTrue(item) ? false : { NOT: item }\n )\n );\n if (folded === false) return false;\n also.push(folded);\n } else if (\n key === \"actor\" &&\n !(\n Object.hasOwn(state.scalars, key) ||\n Object.hasOwn(state.relations, key)\n )\n ) {\n also.push(...conditions(at, member));\n } else if (key === \"$if\") {\n const { control, path: read, ...test } = isRecord(member) ? member : {};\n // A name the words take for the call's instant: refused here, in\n // the policy's own terms.\n if (typeof control !== \"string\")\n refuse(\n `${at}: $if names one control and exactly one test of it`,\n name\n );\n if (control === \"actor\") path(at, read);\n // `$if` names exactly one control: checked above.\n tested = condition(control as string, read, test);\n } else if (key === EXISTS) {\n // Another model's rows, read at their own model: action names are\n // that model's predicates (D7), as in a relation's body.\n const models = isRecord(member) ? Object.keys(member) : [];\n const [model] = models;\n if (models.length !== 1 || !Object.hasOwn(schema, model!))\n refuse(\n `${at}: $exists names exactly one model of the schema and the where its rows must match`,\n name\n );\n // One body below this row, joined to nothing.\n const body = lower(model!, action, (member as Where)[model!], at, [\n ...scopes,\n { model: model! },\n ]);\n if (body === false) return false;\n existing = wrote(exists({ [model!]: body }), {\n exists: [model!, body],\n });\n } else if (member === undefined) {\n // A filter's `undefined` filters nothing: in a rule it would grant\n // every row, as an absent value never should.\n refuse(\n `${at}: ${key} is compared with undefined, which holds for every row; compare with null, a literal or an actor value`,\n name\n );\n } else if (targetOf(name, key) !== undefined) {\n const lowered = relation(name, action, key, member, at, scopes);\n if (lowered === false) return false;\n if (lowered !== undefined) out[key] = lowered;\n } else {\n out[key] = value(at, member, (operand) =>\n enclosingRow(name, key, operand, at, scopes)\n );\n }\n }\n const words = [tested, existing].filter((word) => word !== undefined);\n if (words.length === 0) return and([out, ...also]);\n const held: Where =\n isTrue(out) && words.length === 1\n ? words[0]!\n : { AND: [...(isTrue(out) ? [] : [out]), ...words] };\n written.set(\n held,\n Object.keys(rule).flatMap((key) =>\n key === \"$if\"\n ? [tested!]\n : key === EXISTS\n ? [existing!]\n : Object.hasOwn(out, key)\n ? [{ [key]: out[key] }]\n : []\n )\n );\n return and([held, ...also]);\n };\n\n /**\n * A `{ $row, up }` in a scalar's operand names a column of a row the rule\n * reads (its own at `up: 0`), never past the rule's root, an `$exists`\n * body's, or a recursive relation's body.\n */\n const enclosingRow = (\n name: string,\n key: string,\n operand: { readonly $row: string; readonly up: number },\n at: string,\n scopes: readonly Scope[]\n ): void => {\n const fail = (why: string) =>\n refuse(\n `${at}: ${key} compares { $row: ${JSON.stringify(operand.$row)}, up: ${operand.up} }${why}`,\n name\n );\n const index = scopes.length - 1 - operand.up;\n if (index < 0)\n fail(\n `, which reaches past the rule (${scopes.length - 1} relation bodies deep here)`\n );\n const crossed = scopes.slice(index + 1).find((scope) => scope.sealed);\n if (crossed) fail(` across a recursive relation to ${crossed.model}`);\n const owner = scopes[index]!.model;\n if (!Object.hasOwn(stateOf(owner).scalars, operand.$row))\n fail(`, and ${owner} has no scalar field \"${operand.$row}\"`);\n };\n /** A relation filter: an action name is the target's predicate (D7). */\n const relation = (\n name: string,\n action: string | undefined,\n key: string,\n member: unknown,\n at: string,\n scopes: readonly Scope[]\n ): unknown => {\n const target = targetOf(name, key)!;\n if (typeof member === \"string\") {\n if (!modelOf(target).actions.includes(member))\n refuse(\n `${at} reads ${key} at \"${member}\", which ${target} does not declare`,\n name\n );\n const held = P(target, member);\n return held && { is: held };\n }\n // A field reference, a Date or any other value is not a relation filter.\n if (typeof member === \"object\" && member !== null && !isRecord(member))\n refuse(\n `${at} filters ${key} with a value that is not a filter object, an action name or null`,\n name\n );\n if (!isRecord(member)) return member;\n if (!Object.keys(member).some((op) => QUANTIFIERS.has(op)))\n return lower(target, action, member, at, [...scopes, { model: target }]);\n const out: Record<string, unknown> = {};\n let requiresEmpty = false;\n const scope = { model: target, sealed: member.recurse !== undefined };\n for (const [op, body] of Object.entries(member)) {\n if (!(QUANTIFIERS.has(op) && body !== null)) {\n out[op] = body;\n continue;\n }\n const lowered = lower(target, action, body, at, [...scopes, scope]);\n // A false body: `is`/`some` hold nowhere, `isNot`/`none` everywhere,\n // `every` only where nothing is related.\n if (lowered !== false) out[op] = lowered;\n else if (op === \"is\" || op === \"some\") return false;\n else if (op === \"every\") requiresEmpty = true;\n }\n // `every false` requires an empty relation, which implies any `none`\n // clause. Apply it last so property order cannot weaken the conjunction.\n if (requiresEmpty) out.none = {};\n return Object.keys(out).length === 0 ? undefined : out;\n };\n\n /**\n * Whether `a` implies `b`, both read at `name`, by their structure alone:\n * sound, never complete (a `false` only keeps a conjunct). It is what lets\n * a placement and a move say once what the statement already judges, so\n * the heaviest writes fit a provider's statement limits (plan §11.4).\n */\n const implied = new Map(\n Object.keys(schema).map((name) => [\n name,\n new Map<string, Map<string, boolean>>(),\n ])\n );\n const implies = (name: string, a: Where, b: Where): boolean => {\n if (a === b) return true;\n // Keyed by structure: simplification rebuilds equal guards many times.\n const byModel = implied.get(name)!;\n const left = keyOf(a);\n let row = byModel.get(left);\n if (row === undefined) byModel.set(left, (row = new Map()));\n const right = keyOf(b);\n let answer = row.get(right);\n if (answer === undefined) row.set(right, (answer = provable(name, a, b)));\n return answer;\n };\n const provable = (name: string, a: Where, b: Where): boolean => {\n const right = conjuncts(b);\n if (right.length !== 1)\n return right.every((member) => implies(name, a, member));\n const left = conjuncts(a);\n const [key, given] = headOf(left[0] ?? { AND: [] });\n const [wanted, value] = headOf(right[0]!);\n // `or` writes every alternative as a list.\n if (left.length === 1 && key === \"OR\")\n return (given as Where[]).every((member) => implies(name, member, b));\n if (\n wanted === \"OR\" &&\n // The same: a list of alternatives.\n (value as Where[]).some((member) => implies(name, a, member))\n )\n return true;\n if (left.length !== 1)\n return left.some((member) => implies(name, member, b));\n if (key !== wanted) return false;\n const mine = madeOf(left[0]);\n const theirs = madeOf(right[0]);\n if (mine && theirs && \"provided\" in mine && \"provided\" in theirs) {\n const [tested, test] = mine.provided;\n const [other, wider] = theirs.provided;\n return (\n same(mine, theirs) ||\n (same(tested, other) && narrower(test, wider, \"hasSome\"))\n );\n }\n if (mine && theirs && \"exists\" in mine && \"exists\" in theirs) {\n // EXISTS is monotone: a narrower body finds a row only where a wider one does.\n const [left, narrow] = mine.exists;\n const [right, wide] = theirs.exists;\n return left === right && implies(left, narrow, wide);\n }\n if (!(isRecord(given) && isRecord(value))) return same(given, value);\n if (key === \"NOT\") return implies(name, value, given);\n const target = targetOf(name, key);\n if (target === undefined)\n return (\n same(given, value) ||\n narrower(given, value, \"hasSome\") ||\n narrower(given, value, \"in\")\n );\n // A relation: the same walk, its body implied at the target. Negative\n // quantifiers reverse containment; their wrappers are never scalar keys.\n const ops = [...QUANTIFIERS].filter((op) => Object.hasOwn(value, op));\n if (ops.length === 0) return implies(target, given, value);\n return ops.every(\n (op) =>\n isRecord(given[op]) &&\n isRecord(value[op]) &&\n same(without(given, op), without(value, op)) &&\n (op === \"none\" || op === \"isNot\"\n ? implies(target, value[op], given[op])\n : implies(target, given[op], value[op]))\n );\n };\n /**\n * A conjunct's one key and its member: what a word stands for under the\n * key a rule spells it with.\n */\n const headOf = (clause: Where): [string, unknown] => {\n const word = madeOf(clause);\n return word === undefined\n ? Object.entries(clause)[0]!\n : [\"exists\" in word ? EXISTS : \"$if\", clause];\n };\n /** Stable decomposition lets the implication cache reuse each owned member. */\n const conjunctions = new WeakMap<Where, readonly Where[]>();\n const conjuncts = (clause: Where): readonly Where[] => {\n const known = conjunctions.get(clause);\n if (known !== undefined) return known;\n const members =\n written.get(clause) ??\n (!isRecord(clause) ||\n (Object.keys(clause).length === 1 && !Object.hasOwn(clause, \"AND\"))\n ? [clause]\n : Object.entries(clause).flatMap(([key, member]) =>\n // `and` writes every conjunction as a list.\n key === \"AND\"\n ? (member as Where[]).flatMap(conjuncts)\n : [{ [key]: member }]\n ));\n conjunctions.set(clause, members);\n return members;\n };\n const without = (record: Where, key: string) => {\n const { [key]: _dropped, ...rest } = record;\n return rest;\n };\n /** `{ op: S1, …rest }` against `{ op: S2, …rest }`, with S1 ⊆ S2. */\n const narrower = (given: Where, value: Where, op: string) =>\n Array.isArray(given[op]) &&\n Array.isArray(value[op]) &&\n same(without(given, op), without(value, op)) &&\n // Both lists, checked above.\n (given[op] as unknown[]).every((item) =>\n // The same list.\n (value[op] as unknown[]).some((other) => same(item, other))\n );\n /**\n * R6 reads parameters only after call conditions have folded. A read's\n * guard therefore includes both AND's false siblings and OR's true\n * siblings. Flat sets lose this distinction and can widen a policy.\n * These summaries describe only folding, never row truth or SQL.\n */\n interface ReadSummary {\n readonly yes: Clause;\n readonly no: Clause;\n readonly reads: ReadonlyMap<string, Clause>;\n }\n /**\n * Guards are rebuilt for every candidate a simplification tries, so each\n * one is shared: an equal guard is the first one built, and its negation\n * is derived once.\n */\n const builtGuards = new Map<string, Where>();\n const shared = (guard: Clause): Clause => {\n if (guard === false) return guard;\n const key = keyOf(guard);\n const held = builtGuards.get(key);\n if (held !== undefined) return held;\n builtGuards.set(key, guard);\n return guard;\n };\n const negations = new WeakMap<Where, Clause>();\n const negate = (guard: Clause): Clause => {\n if (guard === false) return {};\n if (isTrue(guard)) return false;\n if (Object.keys(guard).length === 1 && isClause(guard.NOT))\n return guard.NOT;\n let negation = negations.get(guard);\n if (negation === undefined)\n negations.set(\n guard,\n (negation = Array.isArray(guard.AND)\n ? combined(\n false,\n guard.AND.map((member: Where) => negate(member))\n )\n : Array.isArray(guard.OR)\n ? combined(\n true,\n guard.OR.map((member: Where) => negate(member))\n )\n : shared({ NOT: guard }))\n );\n return negation;\n };\n /**\n * One combination of shared guards, built once per distinct operands.\n * Boolean guards, unlike row predicates, have two-valued logic: a\n * conjunction drops repeated factors, never distributes over a disjunction\n * nor expands a truth table.\n */\n const combinations = new Map<string, Clause>();\n const combined = (\n conjunction: boolean,\n guards: readonly Clause[]\n ): Clause => {\n let key = `${conjunction}`;\n for (const operand of guards)\n key += operand === false ? \" F\" : ` ${keyOf(operand)}`;\n let guard = combinations.get(key);\n if (guard === undefined) {\n const all = conjunction ? and(guards) : or(guards);\n combinations.set(\n key,\n (guard = shared(\n conjunction && all && Array.isArray(all.AND)\n ? // A list, checked just above.\n and(distinct(all.AND as Where[]))\n : all\n ))\n );\n }\n return guard;\n };\n const falseSummary: ReadSummary = {\n yes: false,\n no: {},\n reads: new Map(),\n };\n const atomic = (\n reads: ReadonlyMap<string, Clause> = new Map()\n ): ReadSummary => ({\n yes: false,\n no: false,\n reads,\n });\n const combineReads = (\n conjunction: boolean,\n summaries: readonly ReadSummary[]\n ): ReadSummary => {\n const yes = combined(\n conjunction,\n summaries.map((part) => part.yes)\n );\n const no = combined(\n !conjunction,\n summaries.map((part) => part.no)\n );\n const live = negate(conjunction ? no : yes);\n const reads = new Map<string, Clause>();\n for (const part of summaries)\n for (const [key, guard] of part.reads)\n reads.set(\n key,\n combined(false, [\n reads.get(key) ?? false,\n combined(true, [live, guard]),\n ])\n );\n return { yes, no, reads };\n };\n /** Each clause's summary per model: a shared clause is walked once. */\n const summaries = new Map(\n Object.keys(schema).map((name) => [\n name,\n new WeakMap<object, ReadSummary | null>(),\n ])\n );\n const parameterKey = (\n operand: unknown,\n spread: boolean\n ): string | undefined => {\n const word = madeOf(operand);\n return word && \"arg\" in word\n ? JSON.stringify([word.arg[0], word.arg[1] ?? null, spread])\n : undefined;\n };\n const containsParameter = (operand: unknown): boolean =>\n parameterKey(operand, false) !== undefined ||\n (Array.isArray(operand)\n ? operand.some(containsParameter)\n : isRecord(operand) && Object.values(operand).some(containsParameter));\n const readOperators = new Set([\n \"equals\",\n \"not\",\n \"in\",\n \"notIn\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"contains\",\n \"startsWith\",\n \"endsWith\",\n \"has\",\n \"hasSome\",\n \"hasEvery\",\n \"isEmpty\",\n ]);\n /** Ordinary scalar filters contain no call conditions. Exotic operands\n * are left alone rather than guessing how a provider reads their values. */\n const scalarReads = (operand: unknown): ReadSummary | null => {\n const direct = parameterKey(operand, false);\n if (direct !== undefined) return atomic(new Map([[direct, {}]]));\n // An enclosing row's column and the call's instant are written as\n // records of their own, which no read operator spells.\n if (operand === now || madeOf(operand)) return null;\n if (!isRecord(operand)) return containsParameter(operand) ? null : atomic();\n const reads = new Map<string, Clause>();\n for (const [operator, value] of Object.entries(operand)) {\n if (operator === \"mode\" || operator === \"path\") continue;\n if (!readOperators.has(operator)) return null;\n const spread = operator === \"in\" || operator === \"notIn\";\n const key = parameterKey(value, spread);\n if (key !== undefined) reads.set(key, {});\n else if (operator === \"not\" || operator === \"equals\") {\n const nested = scalarReads(value);\n if (nested === null) return null;\n for (const [read, guard] of nested.reads) reads.set(read, guard);\n } else if (spread && Array.isArray(value)) {\n for (const item of value) {\n const read = parameterKey(item, false);\n if (read !== undefined) reads.set(read, {});\n else if (containsParameter(item)) return null;\n }\n } else if (containsParameter(value)) return null;\n }\n // Modifier-only objects (and `{}`) can also be literal JSON. Do not infer\n // folding without the scalar codec's admission decision.\n if (Object.keys(operand).every((key) => key === \"mode\" || key === \"path\"))\n return null;\n return atomic(reads);\n };\n /** The summary of one key of a clause read at `name`, or null where unsupported. */\n const partOf = (\n name: string,\n key: string,\n value: unknown\n ): ReadSummary | null => {\n if (LOGICAL.has(key)) {\n const nested: ReadSummary[] = [];\n for (const body of Array.isArray(value) ? value : [value]) {\n const summary = summarizeReads(name, body);\n if (summary === null) return null;\n nested.push(\n key === \"NOT\"\n ? { yes: summary.no, no: summary.yes, reads: summary.reads }\n : summary\n );\n }\n return combineReads(key !== \"OR\", nested);\n }\n if (Object.hasOwn(stateOf(name).scalars, key)) return scalarReads(value);\n const target = targetOf(name, key);\n if (target === undefined) return null;\n const bodies: unknown[] = [];\n if (\n isRecord(value) &&\n Object.keys(value).some((op) => QUANTIFIERS.has(op))\n ) {\n for (const [op, body] of Object.entries(value))\n if (QUANTIFIERS.has(op)) bodies.push(body);\n else if (op !== \"recurse\" && op !== \"self\") return null;\n } else bodies.push(value);\n const relations: ReadSummary[] = [];\n for (const body of bodies) {\n // A relation keeps its quantifier even when its body folds constant;\n // a null one (`relation: null`, `is: null`) reads nothing.\n const summary = body === null ? atomic() : summarizeReads(target, body);\n if (summary === null) return null;\n relations.push(atomic(summary.reads));\n }\n return combineReads(true, relations);\n };\n const summarizeReads = (\n name: string,\n clause: unknown\n ): ReadSummary | null => {\n if (clause === false) return falseSummary;\n if (!isClause(clause)) return null;\n // A condition guards what it is read with; another model's rows are\n // read like a positive relation's body, wherever the clause is.\n const word = madeOf(clause);\n // A word in a clause's place is a condition or another model's rows:\n // an argument's value and an enclosing row's column stand for values.\n if (word !== undefined) {\n if (\"exists\" in word) {\n const summary = summarizeReads(...word.exists);\n return summary && combineReads(true, [atomic(summary.reads)]);\n }\n return combineReads(true, [\n { yes: clause, no: negate(clause), reads: new Map() },\n ]);\n }\n const cache = summaries.get(name)!;\n const known = cache.get(clause);\n if (known !== undefined) return known;\n const parts: ReadSummary[] = [];\n for (const [key, value] of Object.entries(clause)) {\n const part = partOf(name, key, value);\n if (part === null) {\n cache.set(clause, null);\n return null;\n }\n parts.push(part);\n }\n const result = combineReads(true, parts);\n cache.set(clause, result);\n return result;\n };\n const provesGuard = (name: string, a: Clause, b: Clause): boolean =>\n a === false ||\n (b !== false && (isTrue(b) || same(a, b) || implies(name, a, b)));\n\n /** Equal conditional reads preserve missing/null AND non-list spread\n * refusals. This simplifier injects no guards. An unsupported\n * shape or unproved equivalence simply retains the original expression. */\n const preservesReads = (\n name: string,\n before: Clause,\n after: Clause\n ): boolean => {\n const left = summarizeReads(name, before);\n const right = summarizeReads(name, after);\n if (left === null || right === null) return false;\n // Both callers only delete clauses: no new parameter can appear after.\n // Entries survive even when their guard is false, so guard changes still\n // have to prove equivalence in both directions.\n for (const [key, a] of left.reads) {\n const b = right.reads.get(key) ?? false;\n if (!(provesGuard(name, a, b) && provesGuard(name, b, a))) return false;\n }\n return true;\n };\n /**\n * `members` without each one `covered` says another contains, tried in\n * `order`: a member is dropped only where the judgement `whole` builds of\n * the members left retains the same conditional parameter reads (R6).\n */\n const prune = (\n name: string,\n members: readonly Where[],\n order: readonly number[],\n covered: (at: number, dropped: ReadonlySet<number>) => boolean,\n whole: (members: readonly Where[]) => Clause\n ): Where[] => {\n const dropped = new Set<number>();\n let judgement = whole(members);\n for (const at of order) {\n if (!covered(at, dropped)) continue;\n const reduced = whole(\n members.filter((_, index) => index !== at && !dropped.has(index))\n );\n if (!preservesReads(name, judgement, reduced)) continue;\n judgement = reduced;\n dropped.add(at);\n }\n return members.filter((_, at) => !dropped.has(at));\n };\n /**\n * The conjunction of `clauses` without a member another one implies (or\n * one of `given`, which the same statement already judges), the later\n * first, where the whole judgement, `given` included, keeps its reads.\n */\n const conjoin = (\n name: string,\n clauses: readonly Clause[],\n given: readonly Where[] = []\n ): Clause => {\n const all = and(clauses);\n if (all === false) return false;\n const members = conjuncts(all);\n return and(\n prune(\n name,\n members,\n [...members.keys()].reverse(),\n (at, dropped) => {\n const covers = (other: Where) => implies(name, other, members[at]!);\n return (\n given.some(covers) ||\n members.some(\n (other, index) =>\n index !== at && !dropped.has(index) && covers(other)\n )\n );\n },\n (remaining) => and([...given, ...remaining])\n )\n );\n };\n\n /**\n * Each foreign key `name` holds, with what R4 asks of a value written to\n * it: null where every field of the key may be, or a target the actor\n * views (`P(T, read)`, false where T holds none: R9, fail closed).\n */\n const keysOf = (name: string) =>\n Object.entries(stateOf(name).relations).flatMap(([relation, declared]) => {\n const key = declared[\"~\"].state.foreignKey;\n if (key === undefined) return [];\n const target = targetOf(name, relation)!;\n const action = declarations.get(target)?.read;\n const held = action ? P(target, action) : false;\n const visible = held && { [relation]: { is: held } };\n const nullable = key.fields.every(\n (field) => stateOf(name).scalars[field]?.[\"~\"].state.nullable === true\n );\n const clause = nullable\n ? or([and(key.fields.map((field) => ({ [field]: null }))), visible])\n : visible;\n return [{ relation, fields: key.fields, clause }];\n });\n /**\n * The fields of the rule's own row its bodies compare (`{ $row, up:\n * depth }`). An inlined predicate is relative to its own root and never\n * reaches past it, so it is not walked; a shared clause is walked once per\n * depth.\n */\n const rootReads = (\n name: string,\n clause: unknown,\n depth: number,\n into: Set<string>,\n seen = new Map<object, Set<number>>()\n ): void => {\n const word = madeOf(clause);\n if (word && \"row\" in word) {\n if (word.row[1] === depth) into.add(word.row[0]);\n return;\n }\n if (typeof clause !== \"object\" || clause === null) return;\n // Below the root, an inlined predicate's references stay inside it; at\n // depth 0 it may be a branch of the rule itself (a `P` an action shares).\n if (depth > 0 && inlined.has(clause as Where)) return;\n const depths = seen.get(clause) ?? new Set<number>();\n if (depths.has(depth)) return;\n seen.set(clause, depths.add(depth));\n if (Array.isArray(clause))\n for (const item of clause) rootReads(name, item, depth, into, seen);\n else if (word && \"exists\" in word)\n rootReads(word.exists[0], word.exists[1], depth + 1, into, seen);\n else if (isRecord(clause))\n for (const [key, member] of Object.entries(clause)) {\n const target = LOGICAL.has(key) ? undefined : targetOf(name, key);\n if (target === undefined || !isRecord(member))\n rootReads(name, member, depth, into, seen);\n else if (Object.keys(member).some((op) => QUANTIFIERS.has(op))) {\n for (const op of QUANTIFIERS)\n if (isRecord(member[op]))\n rootReads(target, member[op], depth + 1, into, seen);\n }\n // The to-one shorthand: the body is the related row's own filter.\n else rootReads(target, member, depth + 1, into, seen);\n }\n };\n /**\n * The fields of `name`'s row a clause read at `name` reads: a scalar, the\n * fields a relation joins on (its key, or on the other side the fields of\n * `name` any key references), and a self relation's body where `self`\n * reads the row itself.\n */\n const ownFields = (name: string, clause: unknown, into: Set<string>) => {\n // A condition and another model's rows read no field of the row.\n if (!isRecord(clause)) return;\n for (const [key, member] of Object.entries(clause)) {\n if (LOGICAL.has(key))\n for (const item of Array.isArray(member) ? member : [member])\n ownFields(name, item, into);\n else if (targetOf(name, key) === undefined) into.add(key);\n else {\n const own = relationOf(name, key)!.state.foreignKey;\n if (own !== undefined) for (const field of own.fields) into.add(field);\n else\n for (const other of names.values())\n for (const declared of Object.values(stateOf(other).relations)) {\n const foreign = declared[\"~\"].state.foreignKey;\n if (\n foreign !== undefined &&\n // A relation settles to a model of the schema.\n names.get(declared[\"~\"].settleTarget() as AnyModel) === name\n )\n for (const field of foreign.references) into.add(field);\n }\n if (isRecord(member) && member.self === true)\n for (const op of QUANTIFIERS)\n if (isRecord(member[op])) ownFields(name, member[op], into);\n }\n }\n };\n\n /** One name per predicate of a model: actions, domains, the placement, moves. */\n const unclaimed = (\n names: { has(key: string): boolean },\n key: string,\n at: string,\n name: string\n ) => {\n if (names.has(key))\n refuse(\n `${at}: an action, a domain, the placement or a move already has the name \"${key}\"`,\n name\n );\n };\n // Every check that lowers no rule runs before any model is compiled: the\n // declaration's names (operations, fields, domains, the `as` names), so a\n // misspelt one is refused when the policy is applied, wherever it is.\n const declarations = new Map<string, Declared>();\n for (const name of Object.keys(config.models)) {\n const policy = config.models[name]!;\n const model = modelOf(name);\n const declared = (role: string, action: string | undefined) => {\n if (action !== undefined && !model.actions.includes(action))\n refuse(\n `models.${name}.${role} names \"${action}\", which ${name} does not declare. Declared actions: ${model.actions.join(\", \") || \"none\"}. Add its rule or choose a declared action.`,\n name\n );\n return action;\n };\n // The names `claim` gives out below, but for the moves, which need the\n // placement lowered: the same refusals, at the same places.\n const claimed = new Set<string>(model.actions);\n const claimName = (key: string, at: string) => {\n unclaimed(claimed, key, at, name);\n claimed.add(key);\n };\n const operations = policy.operations ?? {};\n for (const operation of Object.keys(operations))\n if (!OPERATIONS.has(operation))\n refuse(\n `models.${name}.operations.${operation}: not a configurable operation; use read, update or delete (create always uses its own grant)`,\n name\n );\n // The action each entry part takes (K3, OD-3): `operations`, else read,\n // update and delete; a part whose action the model does not declare\n // takes none. Adding actions never changes an operation mapping.\n const byPart: { read?: string; update?: string; delete?: string } = {};\n for (const part of [\"read\", \"update\", \"delete\"] as const) {\n const action = declared(`operations.${part}`, operations[part]) ?? part;\n if (model.actions.includes(action)) byPart[part] = action;\n }\n const writes: Record<string, string> = {};\n const reads: Record<string, string> = {};\n const state = stateOf(name);\n for (const [field, entry] of Object.entries(policy.fields ?? {})) {\n const unknown = isRecord(entry)\n ? Object.keys(entry).find((key) => !FIELD_KEYS.has(key))\n : \"\";\n if (unknown !== undefined)\n refuse(\n `models.${name}.fields.${field}${unknown ? `.${unknown}` : \"\"}: a field entry takes only read and write`,\n name\n );\n const { read, write } = entry;\n if (\n !(\n Object.hasOwn(state.scalars, field) ||\n Object.hasOwn(state.relations, field)\n )\n )\n refuse(\n `models.${name}.fields.${field}: ${name} has no such field`,\n name\n );\n if (write !== undefined) {\n declared(`fields.${field}.write`, write);\n if (write === byPart.update) writes[field] = write;\n else {\n const protectedWrite = `$write:${field}`;\n claimName(protectedWrite, `models.${name}.fields.${field}.write`);\n writes[field] = protectedWrite;\n }\n }\n // A key, a foreign key or a relation is refused by K5's admission.\n if (read === undefined) continue;\n reads[field] = declared(`fields.${field}.read`, read)!;\n }\n claimName(PLACE, `models.${name}.create`);\n const domains = Object.keys(policy.domains ?? {});\n for (const domain of domains)\n claimName(domain, `models.${name}.domains.${domain}`);\n const modes = [...model.actions, ...domains];\n // One `as` name space for every model: the default is no action's.\n if (modes.includes(DEFAULT_MODE))\n refuse(\n `models.${name}: \"${DEFAULT_MODE}\" is the mode a call takes by default, not an action or a domain`,\n name\n );\n declarations.set(name, {\n ...byPart,\n modes,\n writes,\n reads,\n });\n }\n\n /** One listed model's predicates, by name, and its rule entry. */\n const compileModel = (name: string): Compiled => {\n const policy = config.models[name]!;\n const model = modelOf(name);\n const declared = declarations.get(name)!;\n const { writes, ...byPart } = declared;\n const named = new Map<string, Where>();\n // The declaration's names were claimed when the policy was applied; a\n // move's name is new here, and a domain may take one.\n const claim = (key: string, at: string, clause: Where) => {\n unclaimed(named, key, at, name);\n named.set(key, clause);\n };\n for (const action of model.actions)\n named.set(action, and([P(name, action), scope(name, action)]) || FALSE);\n // Field protection narrows the operation's grant. Core chooses one\n // write predicate per field, so compose both permissions here rather\n // than letting a field grant replace a denied or absent update grant.\n for (const [field, { write }] of Object.entries(policy.fields ?? {}))\n if (writes[field] === `$write:${field}`)\n named.set(\n writes[field],\n and([\n byPart.update === undefined ? false : named.get(byPart.update)!,\n named.get(write!)!,\n ]) || FALSE\n );\n // Creation is a named action evaluated on the proposed row. Its placement\n // adds target visibility; moves reuse the row rule without requiring a\n // create credential scope for an update.\n const create = P(name, \"create\");\n const keys = keysOf(name);\n named.set(\n PLACE,\n conjoin(name, [\n create,\n scope(name, \"create\"),\n ...keys.map(({ clause }) => clause),\n ]) || FALSE\n );\n // A move (OD-14): an update writing a field the placement reads is\n // placed again; one writing a key, its target visible.\n const placed = new Set<string>();\n if (create !== false) {\n rootReads(name, create, 0, placed);\n ownFields(name, create, placed);\n }\n const moves: Record<string, string> = {};\n for (const field of new Set([\n ...placed,\n ...keys.flatMap(({ fields }) => fields),\n ])) {\n const move = `move:${field}`;\n const holding = keys.filter(({ fields }) => fields.includes(field));\n // The new row is also judged at what judged the old one (R4), which a\n // move need not say: the read action, and the field's write action when\n // every spelling of the write (the field, a relation holding it) takes\n // the same one (R3).\n const spelled = new Set(\n [field, ...holding.map(({ relation }) => relation)].map(\n (written) => writes[written] ?? byPart.update\n )\n );\n const judged = [byPart.read, ...(spelled.size === 1 ? spelled : [])]\n .filter((action) => action !== undefined)\n .map((action) => named.get(action)!);\n claim(\n move,\n `models.${name}.fields.${field}`,\n conjoin(\n name,\n [\n placed.has(field) ? create : {},\n ...holding.map(({ clause }) => clause),\n ],\n judged\n ) || FALSE\n );\n moves[field] = move;\n }\n for (const [domain, rule] of Object.entries(policy.domains ?? {})) {\n const at = `models.${name}.domains.${domain}`;\n claim(domain, at, lower(name, \"read\", rule, at) || FALSE);\n }\n return entryOf(name, named, { ...declared, moves });\n };\n /**\n * A model's rule entry from its predicates by name: its read action, each\n * field it gates and its `$access`, each write part at its action (an\n * action it does not grant takes no row), the fields whose write takes\n * its own action, the placement of a created row and the moves of an\n * updated one, and the modes that narrow its call's own rows (the\n * default and the read action narrow nothing: `read` holds in every\n * mode).\n */\n const entryOf = (\n name: string,\n named: ReadonlyMap<string, Where>,\n { writes, reads, moves = {}, modes, ...byPart }: Declared\n ): Compiled => {\n const P = (key: string | undefined): object =>\n key === undefined ? nothing : named.get(key)!;\n const names = modelOf(name).actions;\n const root = modes\n .filter((mode) => mode !== byPart.read)\n .map((mode) => when(arg(MODE), mode, P(mode)));\n return {\n predicates: named,\n entry: {\n read: {\n where: P(byPart.read),\n fields: Object.fromEntries(\n Object.entries(reads).map(([field, key]) => [field, gate(P(key))])\n ),\n // Per row, always one boolean for each admitted action.\n ...(names.length > 0 && {\n select: {\n [EVIDENCE_KEY]: facts(\n Object.fromEntries(names.map((fact) => [fact, P(fact)]))\n ),\n },\n }),\n },\n ...(root.length > 0 && { root }),\n create: { check: check(P(PLACE)) },\n update: {\n where: only(P(byPart.update)),\n fields: Object.fromEntries(\n [...new Set([...Object.keys(writes), ...Object.keys(moves)])].map(\n (field) => [\n field,\n {\n ...(writes[field] !== undefined && {\n where: only(P(writes[field])),\n }),\n ...(moves[field] !== undefined && {\n check: check(P(moves[field])),\n }),\n },\n ]\n )\n ),\n },\n delete: { where: only(P(byPart.delete)) },\n acyclic: () => acyclicAt(name),\n },\n };\n };\n\n // A Map: a model may be named `constructor`.\n const compiled = new Map<string, Compiled>();\n /** `name` compiled, once: an unlisted model holds nothing (R9). */\n const modelAt = (name: string): Compiled =>\n memo(compiled, name, () =>\n Object.hasOwn(config.models, name)\n ? compileModel(name)\n : entryOf(name, new Map([[PLACE, FALSE]]), UNLISTED)\n );\n // R4: a self key a predicate recurses over never takes a parent inside\n // the row's own subtree. Any model's predicate may recurse over another's\n // relation, so this is the one fact that needs the whole policy compiled.\n let recursed: ReadonlyMap<string, readonly string[]> | undefined;\n const acyclicAt = (name: string): readonly string[] => {\n if (recursed === undefined) {\n // A model whose rules are refused judges nothing, and every model\n // that inlines one of its predicates is refused with it: what the\n // others recurse over is complete without it.\n for (const each of Object.keys(schema))\n try {\n modelAt(each);\n } catch (error) {\n if (!(error instanceof ClientInitializationError)) throw error;\n }\n // Per model, the self relations holding a key that some compiled\n // predicate recurses over, wherever it is read.\n const found = new Map<string, string[]>();\n // Per model, the clauses already walked there (P is shared, D7).\n const seen = new Map<string, WeakSet<object>>();\n const walk = (name: string, clause: unknown): void => {\n const word = madeOf(clause);\n if (word && \"exists\" in word) walk(...word.exists);\n const walked = memo(seen, name, () => new WeakSet());\n if (!isRecord(clause) || walked.has(clause)) return;\n walked.add(clause);\n for (const [key, member] of Object.entries(clause)) {\n if (LOGICAL.has(key)) {\n for (const item of Array.isArray(member) ? member : [member])\n walk(name, item);\n continue;\n }\n const target = targetOf(name, key);\n if (target === undefined || !isRecord(member)) continue;\n if (\n target === name &&\n member.recurse !== undefined &&\n relationOf(name, key)!.state.foreignKey !== undefined\n ) {\n const list = memo(found, name, () => []);\n if (!list.includes(key)) list.push(key);\n }\n const bodies = [...QUANTIFIERS].filter((op) =>\n Object.hasOwn(member, op)\n );\n for (const body of bodies.length === 0\n ? [member]\n : bodies.map((op) => member[op]))\n walk(target, body);\n }\n };\n for (const [name, model] of compiled)\n for (const clause of model.predicates.values()) walk(name, clause);\n recursed = found;\n }\n return recursed.get(name) ?? NO_RELATIONS;\n };\n const related = tenantOf(config.tenant);\n return {\n declared: Object.fromEntries(\n Object.keys(schema).map((name) => {\n const { writes, reads, ...declared } =\n declarations.get(name) ?? UNLISTED;\n return [name, { ...declared, bound: related(name) }];\n })\n ),\n model: modelAt,\n };\n}\n","// viborm/permissions: one predicate per (model, action), judged in the statement\n// (docs/architecture/rbac-extension-plan.md). An ordinary definition applied\n// through public capabilities; compiling it reads the schema's declarations\n// through the internal `[\"~\"]` accessors.\n//\n// This file is the entry: `permissions(config)` checks the actor schema at once and\n// compiles the policy against the schema it governs. The policy's types are\n// opaque predicates (never a model's `where` type: the 1.2.0 TS2589 lesson);\n// what the types check is the declaration's names: models, fields and actions\n// against the schema and each other, actor paths against the actor schema.\n\nimport type { Operations } from \"../client/exports\";\nimport { ForbiddenError } from \"../errors\";\nimport { args, bound, oneOf } from \"../extensions/args\";\nimport { call } from \"../extensions/call\";\nimport { within } from \"../extensions/confine\";\nimport { extension } from \"../extensions/extension\";\nimport { lazy } from \"../extensions/judge-words\";\nimport { methods } from \"../extensions/methods-part\";\nimport { models as everyOperation, selecting, target } from \"../extensions/on\";\nimport { rule } from \"../extensions/rule\";\nimport type {\n AnyTarget,\n ClientSchema,\n EmptyFacts,\n Extension,\n Facts,\n PlacedArgument,\n Target,\n VibORMConfig,\n} from \"../index\";\nimport type { InferOutput } from \"../validation\";\nimport { type ActorFacts, type ActorPaths, actorContract } from \"./actor\";\nimport {\n type CompiledPolicy,\n compilePolicy,\n DEFAULT_MODE,\n type EVIDENCE_KEY,\n MODE,\n type ModelPolicy,\n type PermissionsConfig,\n type PolicyCompiler,\n policyArguments,\n policyCompiler,\n} from \"./compile\";\nimport type { PolicyModel, Where } from \"./rules\";\n\nexport type { ActorFacts, ActorPaths } from \"./actor\";\nexport type {\n CompiledModel,\n CompiledPolicy,\n ModelPolicy,\n PermissionsConfig,\n} from \"./compile\";\nexport type { PolicyModel, Rule, Where } from \"./rules\";\n\ntype Schema = VibORMConfig[\"schema\"];\n\n// =============================================================================\n// ACTIONS: what each model declares, and the names that must be among them\n// =============================================================================\n\ntype Reserved = \"mandatory\" | \"actions\" | \"operations\" | \"fields\" | \"domains\";\n/** A model's actions when it declares no `actions` graph. */\ntype Crud = \"create\" | \"read\" | \"update\" | \"delete\";\n\ntype RuleKeys<M> = Exclude<keyof M & string, Reserved>;\ntype Space = \" \" | \"\\t\" | \"\\r\" | \"\\n\";\ntype Trim<S extends string> = S extends `${Space}${infer Rest}`\n ? Trim<Rest>\n : S extends `${infer Rest}${Space}`\n ? Trim<Rest>\n : S;\ntype SplitActions<S extends string> = S extends `${infer Head},${infer Tail}`\n ? Trim<Head> | SplitActions<Trim<Tail>>\n : S;\n\n/** Groups contribute their individual actions, never a combined action name. */\ntype DeclaredActions<M> =\n | (M extends { readonly actions: infer A } ? keyof A & string : never)\n | SplitActions<RuleKeys<M>>;\ntype ActionsOf<M> =\n | DeclaredActions<M>\n | (Extract<DeclaredActions<M>, \"update\" | \"delete\"> extends never\n ? never\n : \"read\");\n\ntype InvalidGroup<\n S extends string,\n Seen extends string = never,\n> = S extends `${infer Head},${infer Tail}`\n ? Trim<Head> extends \"\" | Reserved | \"within\" | \"arms\" | Seen\n ? S\n : InvalidGroup<Trim<Tail>, Seen | Trim<Head>>\n : [Seen] extends [never]\n ? never\n : S extends \"\" | Reserved | \"within\" | \"arms\" | Seen\n ? S\n : never;\n\ntype InvalidRuleKeys<M> = {\n [K in RuleKeys<M>]:\n | ([InvalidGroup<K>] extends [never] ? never : K)\n | ([\n Extract<SplitActions<K>, SplitActions<Exclude<RuleKeys<M>, K>>>,\n ] extends [never]\n ? never\n : K);\n}[RuleKeys<M>];\ntype InvalidActionName<S> = S extends string\n ? S extends `${string},${string}` | \"within\" | \"arms\"\n ? S\n : never\n : never;\n\ntype Values<T> = T extends object ? T[keyof T] : never;\ntype NamedActions<M> =\n | Values<M extends { readonly operations: infer O } ? O : never>\n | Values<\n M extends { readonly fields: infer F }\n ? { [K in keyof F]: Values<F[K]> }\n : never\n >\n | (M extends { readonly actions: infer A }\n ? Values<{\n [K in keyof A]: A[K] extends readonly (infer N)[] ? N : never;\n }>\n : never);\n\n/**\n * Retired declaration keys, and rules absent from the model's action list:\n * its explicit graph, else create, read, update and delete. A declaration\n * still widened to its constraint (while a callback in it is inferred) has\n * no keys of its own to check.\n */\ntype UnlistedKeys<M> =\n | Extract<RuleKeys<M>, \"within\" | \"arms\">\n | InvalidRuleKeys<M>\n | (M extends { readonly actions: infer A }\n ?\n | InvalidActionName<keyof A>\n | Exclude<SplitActions<RuleKeys<M>>, keyof A & string>\n : string extends RuleKeys<M>\n ? never\n : Exclude<SplitActions<RuleKeys<M>>, Crud>);\n\ntype UnknownActions<Config extends PermissionsConfig> = {\n [K in keyof Config[\"models\"] & string]: Exclude<\n NamedActions<Config[\"models\"][K]> | UnlistedKeys<Config[\"models\"][K]>,\n | Exclude<ActionsOf<Config[\"models\"][K]>, UnlistedKeys<Config[\"models\"][K]>>\n | undefined\n > extends infer Unknown extends string\n ? [Unknown] extends [never]\n ? never\n : `${K}: ${Unknown}`\n : never;\n}[keyof Config[\"models\"] & string];\n\n// =============================================================================\n// ACTOR PATHS: the ones the declaration spells, against the actor schema\n// =============================================================================\n\n/** Required keys only: an optional key belongs to a payload type, never walked. */\ntype RequiredKeys<T> = {\n [K in keyof T]-?: Record<never, never> extends Pick<T, K> ? never : K;\n}[keyof T];\n\n/**\n * The actor paths a declaration spells: `{ actor: \"path\" }` values and\n * `{ actor: { path: value } }` conditions, found by a walk over the\n * declaration's literal (functions and widened predicates are opaque).\n */\ntype SpelledActorPaths<T> = T extends readonly (infer Item)[]\n ? SpelledActorPaths<Item>\n : T extends (...args: never[]) => unknown\n ? never\n : T extends object\n ? string extends keyof T\n ? never\n :\n | ControlPath<T>\n | {\n [K in RequiredKeys<T> & string]: K extends \"actor\"\n ? T[K] extends string\n ? T[K]\n : ConditionPaths<T[K]>\n : SpelledActorPaths<T[K]>;\n }[RequiredKeys<T> & string]\n : never;\n\n/** Explicit actor parameters and `$if` conditions use the same path vocabulary. */\ntype ControlPath<T> = T extends {\n readonly control: \"actor\";\n readonly path: infer Path extends string;\n}\n ? Path\n : never;\n\ntype ConditionPaths<T> = T extends object\n ? string extends keyof T\n ? never\n : {\n [K in RequiredKeys<T> & string]: T[K] extends object\n ? K | `${K}.${ConditionPaths<T[K]>}`\n : K;\n }[RequiredKeys<T> & string]\n : never;\n\ntype TenantActorPath<Config> = Config extends {\n readonly tenant: { readonly actor: infer Path extends string };\n}\n ? Path\n : never;\ntype UnknownActorPaths<Config extends PermissionsConfig> = Exclude<\n | SpelledActorPaths<Config[\"models\"] | Config[\"mandatory\"]>\n | TenantActorPath<Config>,\n ActorPaths<InferOutput<Config[\"actor\"]>>\n>;\n\ntype ConfigKey = \"actor\" | \"mandatory\" | \"models\" | \"cache\" | \"tenant\";\n\n/** `unknown` when the declaration's names agree; else a member naming the first disagreement. */\ntype DeclarationCheck<Config extends PermissionsConfig> = [\n Exclude<keyof Config, ConfigKey>,\n] extends [never]\n ? ActorAndActionCheck<Config>\n : { readonly \"unknown policy key\": Exclude<keyof Config, ConfigKey> };\n\ntype ActorAndActionCheck<Config extends PermissionsConfig> = [\n UnknownActorPaths<Config>,\n] extends [never]\n ? [UnknownActions<Config>] extends [never]\n ? unknown\n : { readonly \"undeclared action\": UnknownActions<Config> }\n : { readonly \"unknown actor path\": UnknownActorPaths<Config> };\n\n// =============================================================================\n// SCHEMA: the model and field names the declaration spells\n// =============================================================================\n\ntype ScalarsOf<M> = M extends {\n readonly \"~\": { readonly state: { readonly scalars: infer S } };\n}\n ? keyof S\n : never;\ntype RelationsOf<M> = M extends {\n readonly \"~\": { readonly state: { readonly relations: infer R } };\n}\n ? keyof R\n : never;\ntype CreateKeys<M> = M extends { readonly create: infer C }\n ? C extends boolean | ((...args: never[]) => unknown)\n ? never\n : keyof C\n : never;\n\ntype UnknownFields<\n S extends Schema,\n Models extends PermissionsConfig[\"models\"],\n> = {\n [K in keyof Models & keyof S & string]: Exclude<\n | (Models[K] extends { readonly fields: infer F } ? keyof F : never)\n | CreateKeys<Models[K]>,\n | ScalarsOf<S[K]>\n | RelationsOf<S[K]>\n | \"AND\"\n | \"OR\"\n | \"NOT\"\n | \"actor\"\n | \"$if\"\n | \"$exists\"\n > extends infer Unknown extends string\n ? [Unknown] extends [never]\n ? never\n : `${K}.${Unknown}`\n : never;\n}[keyof Models & keyof S & string];\n\n/** `unknown` when every model and field the declaration names is in the schema. */\ntype SchemaCheck<\n S extends Schema,\n Models extends PermissionsConfig[\"models\"],\n> = string extends keyof S\n ? unknown\n : [Exclude<keyof Models, keyof S>] extends [never]\n ? [UnknownFields<S, Models>] extends [never]\n ? unknown\n : { readonly \"unknown field\": UnknownFields<S, Models> }\n : { readonly \"unknown model\": Exclude<keyof Models, keyof S> };\n\n// =============================================================================\n// THE ENTRY: one extension (plan §1.1; K7(b))\n// =============================================================================\n\nconst NAME = \"viborm.permissions\";\n\ntype Listed<Config extends PermissionsConfig> = keyof Config[\"models\"] & string;\ntype ActionOf<\n Config extends PermissionsConfig,\n K extends Listed<Config>,\n> = ActionsOf<Config[\"models\"][K]>;\ntype DomainsOf<M> = M extends { readonly domains: infer D }\n ? keyof D & string\n : never;\n/** Every `as` value: the default, and each listed model's actions and domains. */\ntype ModeOf<Config extends PermissionsConfig> =\n | typeof DEFAULT_MODE\n | {\n [K in Listed<Config>]:\n | ActionOf<Config, K>\n | DomainsOf<Config[\"models\"][K]>;\n }[Listed<Config>];\n\n/**\n * `$as`, declared apart (inline, the factory's contextual type makes `Self`\n * void) as a type, not an interface, so it is a method record.\n */\ntype ScopeOf<Config extends PermissionsConfig> = {\n [K in Listed<Config>]: `${K}.${ActionOf<Config, K>}`;\n}[Listed<Config>];\n\ntype AsMethod<Actor, Scope extends string = string> = {\n /**\n * This client with the actor bound (K6): every call of the view is judged\n * for it. Validated once, here, against the policy's actor schema.\n */\n $as<Self>(this: Self, actor: Actor, scopes?: readonly Scope[]): Self;\n};\n\n/** The fields a model's declaration read-gates (D5). */\ntype GatedOf<M> = M extends { readonly fields: infer F }\n ? {\n [K in keyof F]: F[K] extends { readonly read: string } ? K : never;\n }[keyof F] &\n string\n : never;\n\n/**\n * What the types read of a listed model's rule entry (its `projected` fact): its\n * projection key and its actions (K5's projected overloads), and its\n * read-gated fields (the gated default omit). The predicates stay opaque.\n */\ntype ModelProjection<\n Config extends PermissionsConfig,\n K extends Listed<Config>,\n> = {\n readonly predicates: {\n readonly [name: string]: { readonly [field: string]: unknown };\n };\n} & ([ActionOf<Config, K>] extends [never]\n ? unknown\n : {\n readonly evidence: {\n readonly as: typeof EVIDENCE_KEY;\n readonly names: readonly ActionOf<Config, K>[];\n };\n }) &\n ([GatedOf<Config[\"models\"][K]>] extends [never]\n ? unknown\n : {\n readonly reads: {\n readonly [F in GatedOf<Config[\"models\"][K]>]: string;\n };\n });\n\n/**\n * The policy's arguments as the delegates read them: its mode, on every\n * operation that selects rows. `actor` and `scopes` are bound: no call\n * passes them.\n */\ntype PolicyArguments<Config extends PermissionsConfig> = {\n readonly [MODE]: PlacedArgument<\n ModeOf<Config>,\n PropertyKey,\n Exclude<Operations, \"create\" | \"createMany\">\n >;\n};\n\n/**\n * What applying the policy adds: its arguments, every model of the client\n * governed (a to-one relation reads `| null`), the projection key and the\n * read-gated fields of each listed model, and `$as`.\n */\ntype PermissionsFacts<\n T extends AnyTarget,\n Config extends PermissionsConfig,\n> = Facts<\n AsMethod<ActorFacts<InferOutput<Config[\"actor\"]>>, ScopeOf<Config>>,\n Record<never, never>,\n PolicyArguments<Config>,\n keyof ClientSchema<T[\"config\"]> & string,\n never,\n Record<never, never>,\n Record<never, never>,\n false,\n { readonly [K in Listed<Config>]: ModelProjection<Config, K> }\n>;\n\nexport interface Policy<Config extends PermissionsConfig> {\n readonly config: Config;\n /**\n * The policy compiled against the schema it governs (R1): per model, the\n * rule entry the extension applies, and each credential scope with the\n * scopes it implies. Refusals are `ClientInitializationError`s naming the\n * declaration's path. Public for inspection.\n */\n compile<S extends Schema>(\n schema: S & SchemaCheck<S, Config[\"models\"]>\n ): CompiledPolicy;\n}\n\nconst READS = /^(find|count|aggregate|groupBy|exist)/;\nconst CREATES = /^create/;\nconst UPDATES = /^update/;\n\n/**\n * The action a root operation needs its model to grant (R9, K4), named by\n * its family; an operation of no other family deletes. An upsert is not asked\n * here: each of its arms is judged where it runs, the update where it locates\n * its row and the create in its statement.\n */\nconst actionOf = (operation: string) =>\n READS.test(operation)\n ? \"read\"\n : CREATES.test(operation)\n ? \"create\"\n : UPDATES.test(operation)\n ? \"update\"\n : \"delete\";\n\n/**\n * Every model's modes, alike in name (one argument): the default and the\n * model's read action narrow nothing (`read` already ANDs with every mode,\n * K3); another of its actions or domains narrows by its predicate (R8); a\n * mode it does not declare holds nothing, and a root call naming it is\n * refused before it runs (R9).\n */\ninterface ScopeValues {\n readonly unrestricted: boolean;\n readonly allowed: readonly string[];\n}\nexport interface ScopeSchema {\n readonly \"~standard\": {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: {\n readonly input: readonly string[] | undefined;\n readonly output: ScopeValues;\n };\n validate(\n input: unknown\n ):\n | { readonly value: ScopeValues }\n | { readonly issues: readonly { readonly message: string }[] };\n };\n}\n\n/** Admit the credential once at binding, using the compiler's action closure. */\nfunction scopeSchema(\n implications: Readonly<Record<string, readonly string[]>>\n): ScopeSchema {\n return {\n \"~standard\": {\n version: 1,\n vendor: NAME,\n validate(input) {\n if (input === undefined)\n return { value: { unrestricted: true, allowed: [] } };\n if (!Array.isArray(input))\n return {\n issues: [\n { message: \"Scopes must be an array of model.permission names\" },\n ],\n };\n const allowed = new Set<string>();\n for (const scope of input) {\n if (typeof scope !== \"string\" || !Object.hasOwn(implications, scope))\n return {\n issues: [\n {\n message: `Unknown permission scope: ${typeof scope === \"string\" ? scope : \"expected a string\"}`,\n },\n ],\n };\n for (const implied of implications[scope]!) allowed.add(implied);\n }\n return { value: { unrestricted: false, allowed: [...allowed] } };\n },\n },\n };\n}\n\n/** No client: what an extension written apart from one is built against. */\ntype Untyped = Target<\n VibORMConfig<Record<never, never>>,\n AnyTarget[\"state\"],\n EmptyFacts\n>;\n\n/** Declaration context is field names, not the recursive operation payload. */\ntype PolicyValue<Actor> =\n | string\n | number\n | bigint\n | boolean\n | null\n | Date\n | object\n | {\n readonly actor?: ActorPaths<InferOutput<Actor>>;\n readonly [key: string]: PolicyValue<Actor> | undefined;\n };\n\ntype ModelRelations<Model> = Model extends {\n readonly \"~\": { readonly state: { readonly relations: infer Relations } };\n}\n ? Relations\n : never;\n\ntype ContextualRelation<\n Relation,\n Actor,\n Dynamic extends boolean = true,\n> = Relation extends {\n readonly \"~\": {\n readonly state: {\n readonly target: { readonly getter: () => infer Target };\n };\n };\n}\n ?\n | string\n | (ContextualWhere<Target, Actor, Dynamic> & {\n readonly is?: ContextualRule<Target, Actor, Dynamic> | null;\n readonly isNot?: ContextualRule<Target, Actor, Dynamic> | null;\n readonly some?: ContextualRule<Target, Actor, Dynamic>;\n readonly every?: ContextualRule<Target, Actor, Dynamic>;\n readonly none?: ContextualRule<Target, Actor, Dynamic>;\n })\n : Where | string;\n\ntype ContextualWhere<Model, Actor, Dynamic extends boolean = true> = Where & {\n readonly [Field in ScalarsOf<Model>]?: PolicyValue<Actor>;\n} & {\n readonly [Relation in keyof ModelRelations<Model>]?: ContextualRelation<\n ModelRelations<Model>[Relation],\n Actor,\n Dynamic\n >;\n} & (\"actor\" extends ScalarsOf<Model> | RelationsOf<Model>\n ? unknown\n : {\n readonly actor?: {\n readonly [Path in ActorPaths<InferOutput<Actor>>]?: unknown;\n };\n }) & {\n readonly AND?:\n | ContextualRule<Model, Actor, Dynamic>\n | readonly ContextualRule<Model, Actor, Dynamic>[];\n readonly OR?: readonly ContextualRule<Model, Actor, Dynamic>[];\n readonly NOT?:\n | ContextualRule<Model, Actor, Dynamic>\n | readonly ContextualRule<Model, Actor, Dynamic>[];\n };\n\ntype ContextualRule<Model, Actor, Dynamic extends boolean = true> =\n | boolean\n | ContextualWhere<Model, Actor, Dynamic>\n | (Dynamic extends true\n ? (\n action: string,\n model: PolicyModel\n ) => ContextualRule<Model, Actor, Dynamic>\n : never);\n\n/** Complete only the edited prefix, without enumerating action permutations. */\ntype GroupSuggestions<\n Key extends string,\n Actions extends string,\n> = Key extends `${infer Head},${infer Tail}`\n ? Tail extends `${string},${string}`\n ? `${Head},${GroupSuggestions<Tail, Exclude<Actions, Trim<Head>>>}`\n : `${Head},${Tail extends ` ${string}` ? \" \" : \"\"}${Exclude<Actions, Trim<Head>>}`\n : never;\ntype SuggestedRules<M> =\n | Crud\n | ActionsOf<M>\n | GroupSuggestions<RuleKeys<M>, ActionsOf<M>>;\n\ntype ContextualPolicy<\n C extends VibORMConfig,\n Actor,\n Config extends PermissionsConfig,\n> = string extends keyof C[\"schema\"]\n ? unknown\n : {\n readonly actor: Actor;\n readonly models: {\n readonly [Model in keyof ClientSchema<C>]?: {\n readonly [Key in Reserved]?: Key extends \"mandatory\"\n ? ContextualWhere<ClientSchema<C>[Model], Actor, false>\n : ModelPolicy[Key];\n } & {\n readonly [Action in SuggestedRules<\n Model extends keyof Config[\"models\"]\n ? Config[\"models\"][Model]\n : never\n >]?: ContextualRule<ClientSchema<C>[Model], Actor>;\n } & {\n readonly [Action: string]:\n | ContextualRule<ClientSchema<C>[Model], Actor>\n | undefined;\n };\n };\n };\n\n/**\n * The policy as one extension: `client.$extends(permissions({ actor, models\n * }))`. Model names are inferred from keys independently of callback bodies,\n * so schema admission does not force a context-sensitive Config to its broad\n * constraint; the receiving `$extends` supplies the client before the inline\n * declaration is contextualized. Applied, every model of the client is\n * governed, and every call needs an actor: `db.$as(actor)`.\n */\nexport function permissions<\n T extends AnyTarget,\n const Actor extends object,\n const ModelNames extends string,\n const Config extends PermissionsConfig,\n>(\n config: Config & {\n readonly actor: Actor;\n readonly models: Record<ModelNames, unknown>;\n } & ContextualPolicy<NoInfer<T[\"config\"]>, NoInfer<Actor>, NoInfer<Config>> &\n DeclarationCheck<Config> &\n SchemaCheck<\n NoInfer<T[\"config\"][\"schema\"]>,\n Pick<Config[\"models\"], ModelNames>\n >\n): Policy<Config> & Extension<T, PermissionsFacts<T, Config>>;\nexport function permissions<const Config extends PermissionsConfig>(\n config: Config & DeclarationCheck<Config>\n): unknown {\n const actor = actorContract(config.actor);\n const compile = (schema: Schema) => compilePolicy(config, schema, actor);\n const { modes, scopes } = policyArguments(config);\n /** A bound argument: a read that carries it is never cached, but under `cache: \"allow\"`. */\n const held = (schema: Parameters<typeof bound>[0]) => {\n const value = bound(schema).required();\n return config.cache === \"allow\" ? value : value.volatile();\n };\n /**\n * What applying the policy to one schema made: what the declaration\n * names, checked once, and what a root call may reach. Each model\n * compiles the first time a call needs it, into one state every client of\n * the schema shares; a rule's own refusal comes at its model's first call.\n * Made by the first rule part, which the extension runs once per schema,\n * and again for a schema object that gained or swapped a model: a model\n * the policy lacks would be left open (R9).\n */\n const applied = new WeakMap<Schema, PolicyCompiler>();\n const governed = extension(\n NAME,\n // Every model of the schema, each read when a call first needs it.\n rule<Untyped, (schema: Schema) => object>((schema) => {\n const compiler = policyCompiler(config, { ...schema }, actor);\n applied.set(schema, compiler);\n return Object.fromEntries(\n Object.keys(compiler.declared).map((name) => [\n name,\n lazy(() => compiler.model(name).entry),\n ])\n );\n }),\n // The tenant the policy's own whole-table sets stay in (`tenant`).\n rule<Untyped, (schema: Schema) => object>((schema) =>\n Object.fromEntries(\n // The first rule part, declared before this one, applied the policy.\n Object.entries(applied.get(schema)!.declared).flatMap(\n ([name, model]) =>\n model.bound === undefined\n ? []\n : [[name, { confine: within(model.bound) }]]\n )\n )\n ),\n args({\n actor: held(actor.schema),\n scopes: held(scopeSchema(scopes)),\n [MODE]: oneOf(...modes)\n .default(DEFAULT_MODE)\n .on(selecting),\n }),\n // R9, D3: a call the policy cannot reach is refused before its\n // arguments are validated.\n call((c) => {\n // target(models) selects model calls only: each names its model.\n const model = c.model!;\n const at = applied.get(c.schema)?.declared[model];\n const kind = actionOf(c.operation);\n const mode: unknown = c.values[MODE];\n if (\n !(\n at &&\n Object.hasOwn(config.models, model) &&\n (c.operation === \"upsert\" ||\n (kind === \"create\"\n ? at.modes.includes(kind)\n : at[kind] !== undefined))\n ) ||\n (typeof mode === \"string\" &&\n mode !== DEFAULT_MODE &&\n !at.modes.includes(mode))\n )\n throw new ForbiddenError(model, c.operation);\n }, target(everyOperation)),\n methods(\n (scope: {\n $bind(values: Readonly<Record<string, unknown>>): unknown;\n }) => ({\n $as: (bound: unknown, scopes?: readonly string[]) =>\n scope.$bind({ actor: bound, scopes }),\n })\n )\n );\n return Object.freeze({ ...governed, config, compile });\n}\n"],"mappings":"oiBA6BA,MAAM,GAAW,IAAI,IAAI,CAAC,WAAY,WAAY,UAAU,CAAC,CAE7D,SAAgB,EACd,EACA,EACA,EACO,CACP,MAAM,IAAI,EAA0B,uBAAuB,IAAW,CACpE,KAAM,CAAE,UAAW,qBAAsB,GAAI,GAAS,CAAE,QAAO,CAAG,CAClE,GAAI,IAAU,IAAA,IAAa,CACzB,MACE,aAAiB,MACb,EACI,MAAM,gCAAiC,C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