cvx-kit 0.1.35 → 2.0.0-beta.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 (327) hide show
  1. package/README.md +92 -49
  2. package/dist/agent-tools.d.mts +21 -25
  3. package/dist/agent-tools.mjs +1 -1
  4. package/dist/agent-tools.mjs.map +1 -1
  5. package/dist/auth.d.mts +20 -14
  6. package/dist/auth.mjs +1 -1
  7. package/dist/auth.mjs.map +1 -1
  8. package/dist/components/approvals/_generated/api.d.mts +4 -5
  9. package/dist/components/approvals/_generated/api.mjs.map +1 -1
  10. package/dist/components/approvals/_generated/component.d.mts +0 -2
  11. package/dist/components/approvals/_generated/dataModel.d.mts +1 -3
  12. package/dist/components/approvals/_generated/server.d.mts +0 -2
  13. package/dist/components/approvals/_generated/server.mjs.map +1 -1
  14. package/dist/components/approvals/audit.d.mts +0 -1
  15. package/dist/components/approvals/audit.mjs +1 -1
  16. package/dist/components/approvals/audit.mjs.map +1 -1
  17. package/dist/components/approvals/client.d.mts +0 -1
  18. package/dist/components/approvals/client.mjs +1 -1
  19. package/dist/components/approvals/client.mjs.map +1 -1
  20. package/dist/components/approvals/constants.d.mts +0 -1
  21. package/dist/components/approvals/constants.mjs.map +1 -1
  22. package/dist/components/approvals/convex.config.d.mts +0 -2
  23. package/dist/components/approvals/convex.config.mjs.map +1 -1
  24. package/dist/components/approvals/decisions.d.mts +1 -4
  25. package/dist/components/approvals/decisions.mjs +1 -1
  26. package/dist/components/approvals/decisions.mjs.map +1 -1
  27. package/dist/components/approvals/functions.d.mts +0 -1
  28. package/dist/components/approvals/functions.mjs.map +1 -1
  29. package/dist/components/approvals/health.d.mts +0 -1
  30. package/dist/components/approvals/health.mjs.map +1 -1
  31. package/dist/components/approvals/requests.d.mts +106 -123
  32. package/dist/components/approvals/requests.mjs +1 -1
  33. package/dist/components/approvals/requests.mjs.map +1 -1
  34. package/dist/components/approvals/schema.d.ts +106 -315
  35. package/dist/components/approvals/schema.js +1 -1
  36. package/dist/components/approvals/validators.d.mts +321 -393
  37. package/dist/components/approvals/validators.mjs +1 -1
  38. package/dist/components/approvals/validators.mjs.map +1 -1
  39. package/dist/components/approvals/workflow.d.mts +0 -1
  40. package/dist/components/approvals/workflow.mjs +1 -1
  41. package/dist/components/approvals/workflow.mjs.map +1 -1
  42. package/dist/components/approvals/workflow_steps.d.mts +1 -2
  43. package/dist/components/approvals/workflow_steps.mjs.map +1 -1
  44. package/dist/components/foundation/_generated/api.d.mts +3 -4
  45. package/dist/components/foundation/_generated/api.mjs.map +1 -1
  46. package/dist/components/foundation/_generated/component.d.mts +0 -2
  47. package/dist/components/foundation/_generated/dataModel.d.mts +1 -3
  48. package/dist/components/foundation/_generated/server.d.mts +0 -2
  49. package/dist/components/foundation/_generated/server.mjs.map +1 -1
  50. package/dist/components/foundation/client.d.mts +0 -1
  51. package/dist/components/foundation/client.mjs +1 -1
  52. package/dist/components/foundation/client.mjs.map +1 -1
  53. package/dist/components/foundation/convex.config.d.mts +0 -2
  54. package/dist/components/foundation/convex.config.mjs.map +1 -1
  55. package/dist/components/foundation/functions.d.mts +0 -1
  56. package/dist/components/foundation/functions.mjs.map +1 -1
  57. package/dist/components/foundation/modules/command/command.d.mts +0 -1
  58. package/dist/components/foundation/modules/command/command.mjs.map +1 -1
  59. package/dist/components/foundation/modules/command/lifecycle.d.mts +0 -2
  60. package/dist/components/foundation/modules/command/lifecycle.mjs.map +1 -1
  61. package/dist/components/foundation/modules/observability/observability.d.mts +0 -1
  62. package/dist/components/foundation/modules/observability/observability.mjs.map +1 -1
  63. package/dist/components/foundation/modules/query/query.d.mts +0 -1
  64. package/dist/components/foundation/modules/query/query.mjs.map +1 -1
  65. package/dist/components/foundation/operation.d.mts +2 -3
  66. package/dist/components/foundation/operation.mjs.map +1 -1
  67. package/dist/components/foundation/result.d.mts +0 -1
  68. package/dist/components/foundation/result.mjs.map +1 -1
  69. package/dist/components/foundation/schema.d.ts +0 -2
  70. package/dist/components/foundation/telemetry.d.mts +0 -1
  71. package/dist/components/foundation/telemetry.mjs +1 -1
  72. package/dist/components/foundation/telemetry.mjs.map +1 -1
  73. package/dist/contracts.d.mts +2 -2
  74. package/dist/contracts.mjs +1 -1
  75. package/dist/crud.d.mts +93 -97
  76. package/dist/crud.mjs +1 -1
  77. package/dist/crud.mjs.map +1 -1
  78. package/dist/effect.d.mts +2 -3
  79. package/dist/effect.mjs +1 -1
  80. package/dist/errors.d.mts +2 -4
  81. package/dist/errors.mjs +1 -1
  82. package/dist/errors.mjs.map +1 -1
  83. package/dist/filters.d.mts +1 -1
  84. package/dist/filters.mjs +1 -1
  85. package/dist/idempotency.mjs +1 -1
  86. package/dist/index.d.mts +10 -7
  87. package/dist/index.mjs +1 -1
  88. package/dist/json-schema.d.mts +40 -0
  89. package/dist/json-schema.mjs +2 -0
  90. package/dist/json-schema.mjs.map +1 -0
  91. package/dist/k/compile.d.mts +17 -0
  92. package/dist/k/compile.mjs +2 -0
  93. package/dist/k/compile.mjs.map +1 -0
  94. package/dist/k/dates.d.mts +23 -0
  95. package/dist/k/dates.mjs +2 -0
  96. package/dist/k/dates.mjs.map +1 -0
  97. package/dist/k/formats.d.mts +24 -0
  98. package/dist/k/formats.mjs +2 -0
  99. package/dist/k/formats.mjs.map +1 -0
  100. package/dist/k/index.d.mts +32 -0
  101. package/dist/k/index.mjs +2 -0
  102. package/dist/k/index.mjs.map +1 -0
  103. package/dist/k/issues.d.mts +31 -0
  104. package/dist/k/issues.mjs +2 -0
  105. package/dist/k/issues.mjs.map +1 -0
  106. package/dist/k/kinds.d.mts +81 -0
  107. package/dist/k/kinds.mjs +2 -0
  108. package/dist/k/kinds.mjs.map +1 -0
  109. package/dist/k/object.d.mts +43 -0
  110. package/dist/k/object.mjs +2 -0
  111. package/dist/k/object.mjs.map +1 -0
  112. package/dist/k/parse.d.mts +29 -0
  113. package/dist/k/parse.mjs +2 -0
  114. package/dist/k/parse.mjs.map +1 -0
  115. package/dist/k/schema.d.mts +100 -0
  116. package/dist/k/schema.mjs +2 -0
  117. package/dist/k/schema.mjs.map +1 -0
  118. package/dist/k/standard.d.mts +8 -0
  119. package/dist/k/standard.mjs +2 -0
  120. package/dist/k/standard.mjs.map +1 -0
  121. package/dist/k/types.d.mts +64 -0
  122. package/dist/k/types.mjs +1 -0
  123. package/dist/k.d.mts +8 -0
  124. package/dist/k.mjs +1 -0
  125. package/dist/middleware.d.mts +0 -2
  126. package/dist/middleware.mjs +1 -1
  127. package/dist/middleware.mjs.map +1 -1
  128. package/dist/modules/contracts/binding.d.mts +1 -2
  129. package/dist/modules/contracts/binding.mjs.map +1 -1
  130. package/dist/modules/contracts/contract.d.mts +0 -2
  131. package/dist/modules/contracts/contract.mjs.map +1 -1
  132. package/dist/modules/contracts/convex.d.mts +1 -3
  133. package/dist/modules/contracts/convex.mjs.map +1 -1
  134. package/dist/modules/contracts/domain.d.mts +1 -2
  135. package/dist/modules/contracts/domain.mjs.map +1 -1
  136. package/dist/modules/contracts/errors.d.mts +161 -2
  137. package/dist/modules/contracts/errors.mjs +1 -1
  138. package/dist/modules/contracts/errors.mjs.map +1 -1
  139. package/dist/modules/contracts/exposure.d.mts +1 -2
  140. package/dist/modules/contracts/exposure.mjs.map +1 -1
  141. package/dist/modules/contracts/idempotency.d.mts +1 -2
  142. package/dist/modules/contracts/idempotency.mjs +1 -1
  143. package/dist/modules/contracts/idempotency.mjs.map +1 -1
  144. package/dist/modules/contracts/lazy.d.mts +0 -2
  145. package/dist/modules/contracts/lazy.mjs.map +1 -1
  146. package/dist/modules/contracts/standard.d.mts +7 -5
  147. package/dist/modules/contracts/standard.mjs +1 -1
  148. package/dist/modules/contracts/standard.mjs.map +1 -1
  149. package/dist/modules/contracts/workflow.d.mts +1 -2
  150. package/dist/modules/contracts/workflow.mjs.map +1 -1
  151. package/dist/modules/effect/action.d.mts +6 -7
  152. package/dist/modules/effect/action.mjs +1 -1
  153. package/dist/modules/effect/action.mjs.map +1 -1
  154. package/dist/modules/effect/agent-tools.mjs +1 -1
  155. package/dist/modules/effect/api-runtime.d.mts +1 -2
  156. package/dist/modules/effect/api-runtime.mjs +1 -1
  157. package/dist/modules/effect/api-runtime.mjs.map +1 -1
  158. package/dist/modules/effect/api.d.mts +41 -15
  159. package/dist/modules/effect/api.mjs +1 -1
  160. package/dist/modules/effect/api.mjs.map +1 -1
  161. package/dist/modules/effect/auth.d.mts +5 -6
  162. package/dist/modules/effect/auth.mjs +1 -1
  163. package/dist/modules/effect/auth.mjs.map +1 -1
  164. package/dist/modules/effect/client.d.mts +7 -8
  165. package/dist/modules/effect/client.mjs +1 -1
  166. package/dist/modules/effect/command.d.mts +7 -5
  167. package/dist/modules/effect/command.mjs +1 -1
  168. package/dist/modules/effect/command.mjs.map +1 -1
  169. package/dist/modules/effect/crud.d.mts +272 -206
  170. package/dist/modules/effect/crud.mjs +1 -1
  171. package/dist/modules/effect/crud.mjs.map +1 -1
  172. package/dist/modules/effect/domain.d.mts +5 -6
  173. package/dist/modules/effect/domain.mjs.map +1 -1
  174. package/dist/modules/effect/errors.d.mts +4 -2
  175. package/dist/modules/effect/errors.mjs +1 -1
  176. package/dist/modules/effect/errors.mjs.map +1 -1
  177. package/dist/modules/effect/failure-audit.d.mts +2 -2
  178. package/dist/modules/effect/failure-audit.mjs +1 -1
  179. package/dist/modules/effect/failure-audit.mjs.map +1 -1
  180. package/dist/modules/effect/failures.d.mts +1 -2
  181. package/dist/modules/effect/failures.mjs.map +1 -1
  182. package/dist/modules/effect/foundation.d.mts +0 -2
  183. package/dist/modules/effect/foundation.mjs.map +1 -1
  184. package/dist/modules/effect/idempotency.d.mts +2 -3
  185. package/dist/modules/effect/idempotency.mjs +1 -1
  186. package/dist/modules/effect/idempotency.mjs.map +1 -1
  187. package/dist/modules/effect/input.d.mts +10 -0
  188. package/dist/modules/effect/input.mjs +2 -0
  189. package/dist/modules/effect/input.mjs.map +1 -0
  190. package/dist/modules/effect/normalize.d.mts +0 -2
  191. package/dist/modules/effect/normalize.mjs.map +1 -1
  192. package/dist/modules/effect/operation.d.mts +2 -3
  193. package/dist/modules/effect/operation.mjs.map +1 -1
  194. package/dist/modules/effect/query.d.mts +6 -4
  195. package/dist/modules/effect/query.mjs +1 -1
  196. package/dist/modules/effect/query.mjs.map +1 -1
  197. package/dist/modules/effect/schema.d.mts +0 -2
  198. package/dist/modules/effect/schema.mjs.map +1 -1
  199. package/dist/modules/effect/scope.d.mts +0 -2
  200. package/dist/modules/effect/scope.mjs.map +1 -1
  201. package/dist/modules/effect/workflow.d.mts +4 -5
  202. package/dist/modules/effect/workflow.mjs +1 -1
  203. package/dist/modules/effect/workflow.mjs.map +1 -1
  204. package/dist/modules/foundation/foundation.d.mts +4 -5
  205. package/dist/modules/foundation/foundation.mjs +1 -1
  206. package/dist/modules/foundation/foundation.mjs.map +1 -1
  207. package/dist/modules/foundation/operation.d.mts +2 -3
  208. package/dist/modules/foundation/operation.mjs.map +1 -1
  209. package/dist/namespace.d.mts +104 -0
  210. package/dist/namespace.mjs +2 -0
  211. package/dist/namespace.mjs.map +1 -0
  212. package/dist/oxlint/architecture.d.mts +0 -2
  213. package/dist/oxlint/architecture.mjs +1 -1
  214. package/dist/oxlint/architecture.mjs.map +1 -1
  215. package/dist/oxlint/ast.d.mts +16 -8
  216. package/dist/oxlint/ast.mjs +1 -1
  217. package/dist/oxlint/ast.mjs.map +1 -1
  218. package/dist/oxlint/components.d.mts +0 -2
  219. package/dist/oxlint/components.mjs.map +1 -1
  220. package/dist/oxlint/ownership.d.mts +0 -2
  221. package/dist/oxlint/ownership.mjs +1 -1
  222. package/dist/oxlint/ownership.mjs.map +1 -1
  223. package/dist/oxlint/reserved-files.d.mts +0 -2
  224. package/dist/oxlint/reserved-files.mjs +1 -1
  225. package/dist/oxlint/reserved-files.mjs.map +1 -1
  226. package/dist/oxlint.d.mts +0 -2
  227. package/dist/oxlint.mjs +1 -1
  228. package/dist/oxlint.mjs.map +1 -1
  229. package/dist/querying/cursors.d.mts +27 -9
  230. package/dist/querying/cursors.mjs +1 -1
  231. package/dist/querying/cursors.mjs.map +1 -1
  232. package/dist/querying/execution.d.mts +6 -7
  233. package/dist/querying/execution.mjs +1 -1
  234. package/dist/querying/execution.mjs.map +1 -1
  235. package/dist/querying/failures.d.mts +0 -2
  236. package/dist/querying/failures.mjs +1 -1
  237. package/dist/querying/failures.mjs.map +1 -1
  238. package/dist/querying/filter-boundary.d.mts +18 -9
  239. package/dist/querying/filter-boundary.mjs +1 -1
  240. package/dist/querying/filter-boundary.mjs.map +1 -1
  241. package/dist/querying/filters.d.mts +71 -35
  242. package/dist/querying/filters.mjs +1 -1
  243. package/dist/querying/filters.mjs.map +1 -1
  244. package/dist/querying/planner.d.mts +16 -20
  245. package/dist/querying/planner.mjs +1 -1
  246. package/dist/querying/planner.mjs.map +1 -1
  247. package/dist/querying/relationships.d.mts +6 -6
  248. package/dist/querying/relationships.mjs +1 -1
  249. package/dist/querying/relationships.mjs.map +1 -1
  250. package/dist/querying/search.d.mts +12 -12
  251. package/dist/querying/search.mjs +1 -1
  252. package/dist/querying/search.mjs.map +1 -1
  253. package/dist/querying/security.d.mts +2 -3
  254. package/dist/querying/security.mjs.map +1 -1
  255. package/dist/querying/shared/ast.d.mts +0 -2
  256. package/dist/querying/shared/ast.mjs.map +1 -1
  257. package/dist/querying/shared/contract.d.mts +17 -23
  258. package/dist/querying/shared/contract.mjs +1 -1
  259. package/dist/querying/shared/contract.mjs.map +1 -1
  260. package/dist/querying/shared/evaluate.d.mts +0 -2
  261. package/dist/querying/shared/evaluate.mjs.map +1 -1
  262. package/dist/querying/shared/filters.d.mts +47 -29
  263. package/dist/querying/shared/filters.mjs +1 -1
  264. package/dist/querying/shared/filters.mjs.map +1 -1
  265. package/dist/querying/shared/native-json.d.mts +7 -0
  266. package/dist/querying/shared/native-json.mjs +2 -0
  267. package/dist/querying/shared/native-json.mjs.map +1 -0
  268. package/dist/querying/shared/page.d.mts +19 -22
  269. package/dist/querying/shared/page.mjs +1 -1
  270. package/dist/querying/shared/page.mjs.map +1 -1
  271. package/dist/querying.d.mts +6 -9
  272. package/dist/querying.mjs +1 -1
  273. package/dist/querying.mjs.map +1 -1
  274. package/dist/react/failures.d.mts +0 -2
  275. package/dist/react/failures.mjs.map +1 -1
  276. package/dist/react/optimistic.d.mts +2 -3
  277. package/dist/react/optimistic.mjs.map +1 -1
  278. package/dist/react/pagination-state.d.mts +1 -2
  279. package/dist/react/pagination-state.mjs.map +1 -1
  280. package/dist/react/use-command.d.mts +0 -2
  281. package/dist/react/use-command.mjs.map +1 -1
  282. package/dist/react/use-paginated-list.d.mts +1 -3
  283. package/dist/react/use-paginated-list.mjs +1 -1
  284. package/dist/react/use-paginated-list.mjs.map +1 -1
  285. package/dist/react.d.mts +1 -1
  286. package/dist/react.mjs +1 -1
  287. package/dist/registration.d.mts +65 -0
  288. package/dist/registration.mjs +2 -0
  289. package/dist/registration.mjs.map +1 -0
  290. package/dist/relations-public.d.mts +2 -2
  291. package/dist/relations-public.mjs +1 -1
  292. package/dist/relations.d.mts +55 -46
  293. package/dist/relations.mjs +1 -1
  294. package/dist/relations.mjs.map +1 -1
  295. package/dist/state-machine.d.mts +0 -2
  296. package/dist/state-machine.mjs.map +1 -1
  297. package/dist/table.d.mts +222 -0
  298. package/dist/table.mjs +2 -0
  299. package/dist/table.mjs.map +1 -0
  300. package/dist/tenancy.d.mts +0 -2
  301. package/dist/tenancy.mjs.map +1 -1
  302. package/dist/triggers.d.mts +2 -4
  303. package/dist/triggers.mjs +1 -1
  304. package/dist/triggers.mjs.map +1 -1
  305. package/dist/webhooks.d.mts +9 -9
  306. package/dist/webhooks.mjs +1 -1
  307. package/dist/webhooks.mjs.map +1 -1
  308. package/dist/workflow.mjs +1 -1
  309. package/dist/zod.d.mts +30 -0
  310. package/dist/zod.mjs +2 -0
  311. package/dist/zod.mjs.map +1 -0
  312. package/package.json +51 -29
  313. package/dist/modules/effect/api-zod.d.mts +0 -34
  314. package/dist/modules/effect/api-zod.mjs +0 -2
  315. package/dist/modules/effect/api-zod.mjs.map +0 -1
  316. package/dist/querying/schema-snapshot.d.mts +0 -49
  317. package/dist/querying/schema-snapshot.mjs +0 -2
  318. package/dist/querying/schema-snapshot.mjs.map +0 -1
  319. package/dist/zod-convex.d.mts +0 -10
  320. package/dist/zod-convex.mjs +0 -2
  321. package/dist/zod-convex.mjs.map +0 -1
  322. package/dist/zod-registration.d.mts +0 -15
  323. package/dist/zod-registration.mjs +0 -2
  324. package/dist/zod-registration.mjs.map +0 -1
  325. package/dist/zod-table.d.mts +0 -351
  326. package/dist/zod-table.mjs +0 -2
  327. package/dist/zod-table.mjs.map +0 -1
package/README.md CHANGED
@@ -3,18 +3,24 @@
3
3
  [![CI](https://github.com/ImRLopezAG/cvx-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/ImRLopezAG/cvx-kit/actions/workflows/ci.yml)
4
4
  [![npm](https://img.shields.io/npm/v/cvx-kit)](https://www.npmjs.com/package/cvx-kit)
5
5
 
6
- Reusable Convex application kit: foundation kernels, a generic approvals
7
- component, zod table boundaries, auth-aware function constructors with
8
- per-app role vocabularies, an application trigger registry, and an audited
9
- command protocol.
6
+ Reusable Convex application kit: `k` validators built on native Convex
7
+ validators, table boundaries, foundation kernels, a generic approvals
8
+ component, auth-aware function constructors with per-app role vocabularies, an
9
+ application trigger registry, and an audited command protocol.
10
10
 
11
11
  ```sh
12
12
  bun add cvx-kit
13
13
  # or: npm install cvx-kit
14
14
  ```
15
15
 
16
- Supported versions: Convex `^1.46.0`, Zod `^4.5.4`, Bun `1.3+`, and Node.js
17
- `24+` with npm `11+`. The library runtime is ESM-only.
16
+ Supported versions: Convex `^1.46.0`, convex-helpers `>=0.1.130 <0.2.0`, Bun
17
+ `1.3+`, and Node.js `24+` with npm `11+`. The library runtime is ESM-only.
18
+ Zod is not required. Install `zod` (`^4.6.7`) only to use the optional
19
+ `cvx-kit/zod` interop entry; install `effect` (`>=4.0.1 <5`) for
20
+ `cvx-kit/effect`.
21
+
22
+ To upgrade from cvx-kit 0.1.x (Zod), follow the
23
+ [2.0 migration guide](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/migration-v2.md).
18
24
 
19
25
  ## Toolchain
20
26
 
@@ -56,7 +62,9 @@ Guides:
56
62
 
57
63
  - [`architecture.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/architecture.md) — the layered application shape the kit encodes
58
64
  - [`conventions.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/conventions.md) — the doctrine: folder structure, file anatomy, naming grammar, import rules
59
- - [`zod-table.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/zod-table.md) — one zod shape per entity, masked into every boundary
65
+ - [`k.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/k.md) — the `k` validators: factories, chains, parse and issues, dates, JSON Schema, Zod interop
66
+ - [`table.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/table.md) — one field object per entity, masked into every boundary
67
+ - [`migration-v2.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/migration-v2.md) — moving an app from cvx-kit 0.1.x (Zod) to 2.0
60
68
  - [`auth.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/auth.md) — auth-aware function constructors from injected policy
61
69
  - [`commands.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/commands.md) — Effect command declarations, lifecycle, and migration
62
70
  - [`effect.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/effect.md) — opt-in Effect v4 registries, injected services, and shared API builders
@@ -67,7 +75,7 @@ Guides:
67
75
  - [`crud.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/crud.md) — the CRUD command factory
68
76
  - [`webhooks.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/webhooks.md) — the sanctioned webhook boundary
69
77
  - [`agent-tools.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/agent-tools.md) — agent tools that are audited commands
70
- - [`upgrading.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/upgrading.md) — 0.0.x → 0.1.0, old way → new way
78
+ - [`upgrading.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/upgrading.md) — upgrades within 0.1.x, old way → new way
71
79
  - [`maintainability.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/maintainability.md) — keeping a Convex app maintainable long-term
72
80
  - [`migration.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/migration.md) — restructuring an existing raw Convex project into this architecture
73
81
  - [`llms.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/llms.md) — optional condensed reference for coding agents
@@ -88,48 +96,72 @@ export const listPayments = authQuery({
88
96
  })
89
97
  ```
90
98
 
91
- With `args: contract.queries.x.input`, the property read builds the schema at import. A getter defers it. Declare contract operations as getters too (see the [domain contracts guide](./skills/cvx-kit/references/domain-contracts.md)), so that reading or executing one operation builds and binds only that operation. Keep the trigger registry out of query modules with `createAuthReaders` (see `cvx-kit/auth` below). Validation is identical in every form.
99
+ With `args: contract.queries.x.input`, the property read builds the schema at import. A getter defers it, which makes the getter form the recommended one: on the benchmark app (about 30 tables, 14 functions) module load drops from 8.43 ms to 6.30 ms. The property form stays supported, and the v2 codemod writes getters unless given `--no-getters`. Declare contract operations as getters too (see the [domain contracts guide](./skills/cvx-kit/references/domain-contracts.md)), so that reading or executing one operation builds and binds only that operation. Keep the trigger registry out of query modules with `createAuthReaders` (see `cvx-kit/auth` below). Validation is identical in every form.
92
100
 
93
101
  Two more things keep the deferral intact. First, a `paginationOpts(...)` or `pageDto(...)` call at module scope outside a contract still builds at import, so put it behind a getter or inside the operation that uses it. Second, pass Convex's generated builders (`query`, `mutation`, ...) to the kit constructors. A wrapper that spreads or copies the definition reads its getters at registration.
94
102
 
95
103
  ## Modules
96
104
 
97
- ### `cvx-kit/zod-table`
105
+ ### `cvx-kit/k`
106
+
107
+ Schemas are written with `k`. Each `k` schema carries a plain native Convex
108
+ validator, which is what Convex receives for args, returns and tables. The kit
109
+ runs checks, defaults, normalisers, refinements and transforms only where a
110
+ schema declares them; a function with none does no validation work of its own.
111
+
112
+ ```ts
113
+ import { k } from 'cvx-kit/k'
114
+
115
+ const renameArgs = k.object({
116
+ id: k.id('documents'),
117
+ title: k.string().trim().min(1).max(200),
118
+ })
119
+ type RenameArgs = k.input<typeof renameArgs>
120
+ ```
121
+
122
+ Failed declared checks throw a `ConvexError` with data
123
+ `{ code: 'VALIDATION', issues: [{ path, code, message }] }`. `k` schemas
124
+ implement Standard Schema v1; `toJsonSchema` (`cvx-kit/json-schema`) and
125
+ `toZod` (`cvx-kit/zod`) convert them for agent tools and Zod-only libraries.
126
+ See the [`k` guide](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/k.md).
98
127
 
99
- One zod shape per entity, masked into every boundary it crosses:
128
+ ### `cvx-kit/table`
129
+
130
+ One field object per entity, masked into every boundary it crosses:
100
131
 
101
132
  ```ts
102
- import { zodTable } from 'cvx-kit/zod-table'
133
+ import { k } from 'cvx-kit/k'
134
+ import { kTable } from 'cvx-kit/table'
103
135
 
104
- export const documents = zodTable(
136
+ export const documents = kTable(
105
137
  'documents',
106
- (id) => ({
107
- title: z.string(),
108
- ownerId: id('users'),
109
- secretNote: z.string(),
110
- }),
138
+ {
139
+ title: k.string(),
140
+ ownerId: k.id('users'),
141
+ secretNote: k.string(),
142
+ },
111
143
  {
112
144
  commandFields: ['title'], // what a command may say
113
145
  publicFields: ['title', 'ownerId'], // the DTO allowlist
114
146
  },
115
147
  )
116
148
  // documents.table → defineTable(...) for schema.ts
117
- // documents.toPublicDto(row) → projects AND re-parses (runtime redaction)
149
+ // documents.toPublicDto(row) → projects AND re-checks (runtime redaction)
118
150
  ```
119
151
 
120
152
  For fields shared across tables, create a reusable declaration function:
121
153
 
122
154
  ```ts
123
- import { createTable } from 'cvx-kit/zod-table'
155
+ import { createTable } from 'cvx-kit/table'
124
156
 
125
- const customTable = createTable({ ref: z.string(), nextActivity: z.string() })
126
- const tasks = customTable('tasks', () => ({ title: z.string() }))
127
- const projects = customTable('projects', () => ({ name: z.string() }))
157
+ const customTable = createTable({ ref: k.string(), nextActivity: k.string() })
158
+ const tasks = customTable('tasks', { title: k.string() })
159
+ const projects = customTable('projects', { name: k.string() })
128
160
  ```
129
161
 
130
- It accepts the same arguments and returns the same boundary as `zodTable`.
162
+ It accepts the same arguments and returns the same boundary as `kTable`.
131
163
  Table-specific fields cannot repeat shared field names. See the
132
- [`zod-table` guide](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/zod-table.md)
164
+ [`table` guide](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/table.md)
133
165
  for field masks and examples.
134
166
 
135
167
  Every table gets `createdAt`, `updatedAt`, and `archivedAt` baked in —
@@ -138,13 +170,13 @@ opinionated, server-owned, always excluded from inserts and commands
138
170
  `timestamps` trigger once and they maintain themselves; `archivedAt` stays
139
171
  under application control.
140
172
 
141
- `zodVariantTable` covers discriminated-union tables; `jsonSafeZid` keeps
142
- LLM-tool JSON schemas primitive while preserving the `Id<...>` type.
173
+ `kVariantTable` covers discriminated-union tables. Tool masks keep `k.id(...)`;
174
+ `toJsonSchema` renders ids as strings while the `Id<...>` type is preserved.
143
175
 
144
176
  ### `cvx-kit/relations` and `cvx-kit/querying`
145
177
 
146
178
  See the [querying guide](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/querying.md),
147
- [DTO parameters](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/zod-table.md#public-dto-parameters), and
179
+ [DTO parameters](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/table.md#public-dto-parameters), and
148
180
  [consumer rule reference](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/oxlint.md#dto-and-pagination-diagnostics).
149
181
 
150
182
  Declare relationships once in `convex/relations.ts`, then configure the engine
@@ -169,7 +201,7 @@ export const relations = defineRelations({ tasks, labels, edges }, (r) => ({
169
201
  }))
170
202
  ```
171
203
 
172
- The tables can be `zodTable`, `tenantTable`, or three-argument `zodVariantTable` boundaries, with
204
+ The tables can be `kTable`, `createTable`, `tenantTable`, or three-argument `kVariantTable` boundaries, with
173
205
  indexes supporting each declared lookup. Names can distinguish multiple edges
174
206
  to the same table; references can point to the same table. A one edge returns a
175
207
  public DTO or `null`. A many edge returns a bounded native page. Junction output
@@ -197,9 +229,8 @@ import { relations } from '../convex/relations'
197
229
  test('relation registry is valid', () => verifyRelations(relations))
198
230
  ```
199
231
 
200
- Relation DTOs support `.refine()`. They reject opaque `.superRefine()` and
201
- `.check()` callbacks; express those validations with `.refine()` instead.
202
- Captured callbacks still observe application state through their closures.
232
+ Relation DTOs only validate; they never transform stored values. Refinement
233
+ closures still observe application state.
203
234
 
204
235
  Variant tables keep their discriminated public unions. Use the relation callback's
205
236
  second argument, `branch('payments', 'creditor_payment').creditorId`, for a
@@ -227,10 +258,8 @@ output, index, order, relation ancestry, principal/tenant/security scope, and
227
258
  registry/policy/engine versions. Page-size changes alone remain valid. Retain
228
259
  old keys during rotation when existing cursors should continue working.
229
260
 
230
- Relation registration captures and validates schemas eagerly; eligible private
231
- DTO schemas reconstruct on first projection. Public helper schemas stay fresh.
232
- See [registry capture and compatibility](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/querying.md#registry-capture-and-private-dtos)
233
- for eager fallback and the unsupported side-effecting internal Proxy boundary.
261
+ Private DTO schemas are built on a table's first projection, and helper schemas
262
+ are memoised. See [registry capture](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/querying.md#registry-capture-and-private-dtos).
234
263
 
235
264
  Use the registry's validators in domain contracts and an authenticated Query
236
265
  registry handler:
@@ -298,12 +327,12 @@ and custom sorts are outside this API.
298
327
  Root full-text search uses a declared native search index and keeps native relevance order:
299
328
 
300
329
  ```ts
301
- const page = await querying(ctx).tasks
302
- .search('search_text', input.text)
303
- .where({ status: 'open' })
304
- .include({ finance: 'if-permitted' })
305
- .with({ labels: true })
306
- .paginate({ numItems: 25, cursor: input.cursor, scanLimit: 250 })
330
+ const page = await querying(ctx)
331
+ .tasks.search('search_text', input.text)
332
+ .where({ status: 'open' })
333
+ .include({ finance: 'if-permitted' })
334
+ .with({ labels: true })
335
+ .paginate({ numItems: 25, cursor: input.cursor, scanLimit: 250 })
307
336
  ```
308
337
 
309
338
  Declare `search_text` on the exact native table registered in `relations`.
@@ -333,12 +362,26 @@ The declared contract sanitizes unknown failures; do not transport raw exception
333
362
  See the [search contract](skills/cvx-kit/references/querying.md#root-full-text-search)
334
363
  and [React list protocol](skills/cvx-kit/references/client-list.md).
335
364
 
365
+ Argument and compact-filter validation failures throw `KValidationError`
366
+ (`ConvexError({ code: 'VALIDATION', issues })`) by default. Pass `argumentFailure: 'declared'`
367
+ to `createAuthFunctions` / `createAuthReaders` to throw the built-in
368
+ `argumentErrors` `INVALID_ARGUMENTS` envelope instead (bounded `{ path, code, message }`
369
+ issues, never the input), or a function returning the value to throw. Decode it
370
+ with `combineErrorContracts(appErrors, argumentErrors)` from `cvx-kit/errors`; see
371
+ [client failures](skills/cvx-kit/references/client-failures.md#argument-validation-failures).
372
+
373
+ Set `argumentFailure` on `createEffectFoundation` for Effect command and query
374
+ `input` validation, including direct `exec` calls. The default preserves the
375
+ decoder failure (`UnknownFailure` at endpoints with declared error projection).
376
+ Opt in to `'declared'` or supply a hook that receives
377
+ `{ source: 'arguments', issues }` and returns the value to throw.
378
+
336
379
  For manual projection, `tasks.toPublicDto(row)` still omits IDs and unselected
337
380
  storage fields. `tasks.toPublicDto(row, true)` or `{ _id: true }` adds the branded
338
381
  ID only. Computed extensions use matching schemas:
339
382
 
340
383
  ```ts
341
- const extend = { url: z.url() }
384
+ const extend = { url: k.string() }
342
385
  const dto = tasks.toPublicDto(row, {
343
386
  _id: true,
344
387
  extend,
@@ -455,7 +498,7 @@ policies once with `createEffectFoundation`, and declare each handler inside
455
498
  ```ts
456
499
  import { createEffectFoundation } from 'cvx-kit/effect'
457
500
  import type { AuditEntryInput } from 'cvx-kit/components/foundation'
458
- import { z } from 'zod'
501
+ import { k } from 'cvx-kit/k'
459
502
 
460
503
  type Host = {
461
504
  actorId: string
@@ -469,13 +512,13 @@ const { Command } = createEffectFoundation({
469
512
  },
470
513
  writeAudit: (host: Host, entry) => host.appendAudit(entry),
471
514
  })
472
- const renameInput = z.object({ id: z.string(), title: z.string() }).strict()
515
+ const renameInput = k.object({ id: k.string(), title: k.string() })
473
516
  export const commands = Command({
474
517
  context: (host: Host) => host,
475
518
  operations: ({ command }) => ({
476
519
  'documents.rename': command({
477
520
  input: renameInput,
478
- result: z.object({ ok: z.literal(true) }).strict(),
521
+ result: k.object({ ok: k.literal(true) }),
479
522
  classification: 'business',
480
523
  handler: async (input, context) => {
481
524
  await context.rename(input.id, input.title)
@@ -489,12 +532,12 @@ export const commands = Command({
489
532
  }),
490
533
  }),
491
534
  })
492
- export const executeRename = (input: z.input<typeof renameInput>, host: Host) =>
535
+ export const executeRename = (input: k.input<typeof renameInput>, host: Host) =>
493
536
  commands.exec('documents.rename', input, host)
494
537
  ```
495
538
 
496
539
  `exec` returns a lazy Effect even for ordinary async handlers. Shared
497
- `effectApiBuilder` / `effectZodApiBuilder` constructors provide invocation-local
540
+ `effectApiBuilder` constructors provide invocation-local
498
541
  services and execute it; domain code can compose `Effect.gen` and `Effect.fn`
499
542
  without starting another runner. Commands validate inputs and results, enforce
500
543
  permissions and guards, and write audit entries in the mutation transaction.
@@ -629,7 +672,7 @@ One-time setup (already-published package required first):
629
672
 
630
673
  ## Roadmap
631
674
 
632
- See [ROADMAP.md](https://github.com/ImRLopezAG/cvx-kit/blob/main/ROADMAP.md) — milestones from 0.1.0 through 1.0.0.
675
+ See [ROADMAP.md](https://github.com/ImRLopezAG/cvx-kit/blob/main/ROADMAP.md) for milestones.
633
676
 
634
677
  Optional request context can be added through the existing Effect API adapter's
635
678
  `context` callback. Bind selected registries with `commands.withContext(value)`
@@ -1,26 +1,33 @@
1
+ import { KType } from "./k/types.mjs";
2
+ import { KObject } from "./k/object.mjs";
3
+ import "./k.mjs";
4
+ import { convexPaginationOptions } from "./querying/filters.mjs";
1
5
  import { OperationExecutor, OperationPublicResult, OperationTool, OperationToolConverter, OperationToolDefinition, OperationToolJsonSchema, OperationToolOutcome, SelectedOperation, bindOperationExecutor, createOperationTools, operationToolDialect, selectOperation } from "./modules/contracts/exposure.mjs";
2
- import { z } from "zod";
3
- //#region src/agent-tools.d.ts
4
6
  /**
5
- * A framework-agnostic tool record: directly spreadable into
6
- * @convex-dev/agent's createTool ({ description, args, handler }) and
7
- * adaptable to ai-sdk tool(). The kit imports neither framework — checked
8
- * against registry snapshots on 2026-08-14; re-verify at install time.
7
+ * A framework-agnostic tool record: `args` is a `k` schema, which implements Standard Schema v1
8
+ * (`args['~standard']`) and parses with `args.parse`. For a JSON Schema of the input (ids are strings,
9
+ * `.describe()` texts carry through) call `toJsonSchema(record.args)` from `cvx-kit/json-schema`; for a
10
+ * framework that only takes Zod, `toZod(record.args)` from `cvx-kit/zod`. The kit imports no agent
11
+ * framework.
9
12
  */
10
13
  export type AgentToolRecord<Result = unknown, Context = never, Input = never> = {
11
14
  name: string;
12
15
  description: string;
13
- args: z.ZodType;
16
+ args: KType;
14
17
  handler: (ctx: Context, input: Input) => Promise<Result>;
15
18
  };
16
19
  type ToolTable = {
17
- tableName: string;
18
- tools: {
19
- insert: z.ZodType;
20
- update: z.ZodType;
21
- id: z.ZodType;
20
+ readonly tableName: string;
21
+ readonly tools: {
22
+ readonly insert: KType;
23
+ readonly update: KType;
24
+ readonly id: KType;
22
25
  };
23
26
  };
27
+ /** The `list` tool input: Convex's pagination options under `paginationOpts`. */
28
+ export type AgentListArgs = KObject<{
29
+ readonly paginationOpts: ReturnType<typeof convexPaginationOptions>;
30
+ }>;
24
31
  type ToolHandler<Result> = (ctx: never, input: never) => Promise<Result>;
25
32
  export type AgentToolHandlers<Result = unknown> = {
26
33
  /** Mutations: route through command executors — agents get audited commands. */
@@ -31,19 +38,9 @@ export type AgentToolHandlers<Result = unknown> = {
31
38
  get?: ToolHandler<Result>;
32
39
  list?: ToolHandler<Result>;
33
40
  };
34
- declare const listArgs: z.ZodObject<{
35
- paginationOpts: z.ZodObject<{
36
- numItems: z.ZodNumber;
37
- cursor: z.ZodUnion<readonly [z.ZodString, z.ZodNull]>;
38
- endCursor: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNull]>>;
39
- id: z.ZodOptional<z.ZodNumber>;
40
- maximumRowsRead: z.ZodOptional<z.ZodNumber>;
41
- maximumBytesRead: z.ZodOptional<z.ZodNumber>;
42
- }, z.core.$strict>;
43
- }, z.core.$strict>;
44
41
  /**
45
42
  * Emits agent tool definitions from the existing table tool masks: args are
46
- * the masks (jsonSafeZid keeps ids primitive in generated JSON schemas),
43
+ * the masks (`k` schemas; ids are strings in their JSON Schema),
47
44
  * names are `<tableName>_<verb>`, and only the kinds you supply handlers for
48
45
  * are emitted. Wire mutation handlers to createCrudCommands executors (or
49
46
  * your own) so every agent action is an audited command.
@@ -54,9 +51,8 @@ export declare function createAgentTools<Table extends ToolTable, Handlers exten
54
51
  export type AgentTools<Table extends ToolTable, Handlers extends AgentToolHandlers> = Partial<{ [Verb in keyof Handlers & keyof AgentToolHandlers as `${Table['tableName']}_${Verb}`]: {
55
52
  name: string;
56
53
  description: string;
57
- args: Verb extends 'create' ? Table['tools']['insert'] : Verb extends 'update' ? Table['tools']['update'] : Verb extends 'list' ? typeof listArgs : Table['tools']['id'];
54
+ args: Verb extends 'create' ? Table['tools']['insert'] : Verb extends 'update' ? Table['tools']['update'] : Verb extends 'list' ? AgentListArgs : Table['tools']['id'];
58
55
  handler: NonNullable<Handlers[Verb]>;
59
56
  }; }>;
60
- //#endregion
61
57
  export { type OperationExecutor, type OperationPublicResult, type OperationTool, type OperationToolConverter, type OperationToolDefinition, type OperationToolJsonSchema, type OperationToolOutcome, type SelectedOperation, bindOperationExecutor, createOperationTools, operationToolDialect, selectOperation };
62
58
  //# sourceMappingURL=agent-tools.d.mts.map
@@ -1,2 +1,2 @@
1
- import{bindOperationExecutor as e,createOperationTools as t,operationToolDialect as n,selectOperation as r}from"./modules/contracts/exposure.mjs";import{convexToZod as i}from"convex-helpers/server/zod4";import{paginationOptsValidator as a}from"convex/server";import{z as o}from"zod";const s=o.object({paginationOpts:i(a)}).strict();function c(e,t,n){let r=e.tableName,i={create:e.tools.insert,update:e.tools.update,archive:e.tools.id,get:e.tools.id,list:s},a={create:`Create a ${r} record`,update:`Update fields of an existing ${r} record`,archive:`Archive (soft-delete) a ${r} record`,get:`Fetch one ${r} record by id`,list:`List ${r} records, paginated`},o={};for(let e of[`create`,`update`,`archive`,`get`,`list`]){let s=t[e];s&&(o[`${r}_${e}`]={name:`${r}_${e}`,description:n?.descriptions?.[e]??a[e],args:i[e],handler:s})}return o}export{e as bindOperationExecutor,c as createAgentTools,t as createOperationTools,n as operationToolDialect,r as selectOperation};
1
+ import{k as e}from"./k/index.mjs";import{convexPaginationOptions as t}from"./querying/filters.mjs";import{bindOperationExecutor as n,createOperationTools as r,operationToolDialect as i,selectOperation as a}from"./modules/contracts/exposure.mjs";function o(e,t,n){let r=e.tableName,i={create:()=>e.tools.insert,update:()=>e.tools.update,archive:()=>e.tools.id,get:()=>e.tools.id,list:c},a={create:`Create a ${r} record`,update:`Update fields of an existing ${r} record`,archive:`Archive (soft-delete) a ${r} record`,get:`Fetch one ${r} record by id`,list:`List ${r} records, paginated`},o={};for(let e of[`create`,`update`,`archive`,`get`,`list`]){let s=t[e];s&&(o[`${r}_${e}`]={name:`${r}_${e}`,description:n?.descriptions?.[e]??a[e],args:i[e](),handler:s})}return o}let s;function c(){return s??=e.object({paginationOpts:t()})}export{n as bindOperationExecutor,o as createAgentTools,r as createOperationTools,i as operationToolDialect,a as selectOperation};
2
2
  //# sourceMappingURL=agent-tools.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-tools.mjs","names":["listArgs","z","convexToZod","paginationOptsValidator","createAgentTools","name","table","masks","defaults","tools","verb","handler","handlers","options","bindOperationExecutor","createOperationTools","operationToolDialect","selectOperation"],"sources":["../src/agent-tools.ts"],"sourcesContent":["import { convexToZod } from 'convex-helpers/server/zod4'\nimport { paginationOptsValidator } from 'convex/server'\nimport { z } from 'zod'\n\n/**\n * A framework-agnostic tool record: directly spreadable into\n * @convex-dev/agent's createTool ({ description, args, handler }) and\n * adaptable to ai-sdk tool(). The kit imports neither framework — checked\n * against registry snapshots on 2026-08-14; re-verify at install time.\n */\nexport type AgentToolRecord<Result = unknown, Context = never, Input = never> = {\n\tname: string\n\tdescription: string\n\targs: z.ZodType\n\thandler: (ctx: Context, input: Input) => Promise<Result>\n}\n\ntype ToolTable = {\n\ttableName: string\n\ttools: {\n\t\tinsert: z.ZodType\n\t\tupdate: z.ZodType\n\t\tid: z.ZodType\n\t}\n}\n\ntype ToolHandler<Result> = (ctx: never, input: never) => Promise<Result>\n\nexport type AgentToolHandlers<Result = unknown> = {\n\t/** Mutations: route through command executors — agents get audited commands. */\n\tcreate?: ToolHandler<Result>\n\tupdate?: ToolHandler<Result>\n\tarchive?: ToolHandler<Result>\n\t/** Reads: caller-supplied query handlers (reads do not route through commands). */\n\tget?: ToolHandler<Result>\n\tlist?: ToolHandler<Result>\n}\n\nconst listArgs = z.object({ paginationOpts: convexToZod(paginationOptsValidator) }).strict()\n\n/**\n * Emits agent tool definitions from the existing table tool masks: args are\n * the masks (jsonSafeZid keeps ids primitive in generated JSON schemas),\n * names are `<tableName>_<verb>`, and only the kinds you supply handlers for\n * are emitted. Wire mutation handlers to createCrudCommands executors (or\n * your own) so every agent action is an audited command.\n */\nexport function createAgentTools<Table extends ToolTable, Handlers extends AgentToolHandlers>(\n\ttable: Table,\n\thandlers: Handlers,\n\toptions?: { descriptions?: Partial<Record<keyof AgentToolHandlers, string>> },\n) {\n\tconst name = table.tableName\n\tconst masks: Record<keyof AgentToolHandlers, z.ZodType> = {\n\t\tcreate: table.tools.insert,\n\t\tupdate: table.tools.update,\n\t\tarchive: table.tools.id,\n\t\tget: table.tools.id,\n\t\tlist: listArgs,\n\t}\n\tconst defaults: Record<keyof AgentToolHandlers, string> = {\n\t\tcreate: `Create a ${name} record`,\n\t\tupdate: `Update fields of an existing ${name} record`,\n\t\tarchive: `Archive (soft-delete) a ${name} record`,\n\t\tget: `Fetch one ${name} record by id`,\n\t\tlist: `List ${name} records, paginated`,\n\t}\n\tconst tools: Record<string, AgentToolRecord> = {}\n\tfor (const verb of ['create', 'update', 'archive', 'get', 'list'] as const) {\n\t\tconst handler = handlers[verb]\n\t\tif (!handler) continue\n\t\ttools[`${name}_${verb}`] = {\n\t\t\tname: `${name}_${verb}`,\n\t\t\tdescription: options?.descriptions?.[verb] ?? defaults[verb],\n\t\t\targs: masks[verb],\n\t\t\thandler,\n\t\t}\n\t}\n\t// SAFETY: each emitted key combines this table name with a supplied verb; its handler and schema come from those same inputs.\n\treturn tools as AgentTools<Table, Handlers>\n}\n\nexport type AgentTools<Table extends ToolTable, Handlers extends AgentToolHandlers> = Partial<{\n\t[Verb in keyof Handlers & keyof AgentToolHandlers as `${Table['tableName']}_${Verb}`]: {\n\t\tname: string\n\t\tdescription: string\n\t\targs: Verb extends 'create'\n\t\t\t? Table['tools']['insert']\n\t\t\t: Verb extends 'update'\n\t\t\t\t? Table['tools']['update']\n\t\t\t\t: Verb extends 'list'\n\t\t\t\t\t? typeof listArgs\n\t\t\t\t\t: Table['tools']['id']\n\t\thandler: NonNullable<Handlers[Verb]>\n\t}\n}>\nexport {\n\tselectOperation,\n\tbindOperationExecutor,\n\tcreateOperationTools,\n\toperationToolDialect,\n\ttype SelectedOperation,\n\ttype OperationExecutor,\n\ttype OperationPublicResult,\n\ttype OperationToolJsonSchema,\n\ttype OperationToolConverter,\n\ttype OperationToolDefinition,\n\ttype OperationToolOutcome,\n\ttype OperationTool,\n} from './modules/contracts/exposure'\n"],"mappings":"2RAsCA,MAAMA,EAAWC,EAAE,OAAO,CAAE,eAAgBC,EAAYC,CAAuB,CAAE,CAAC,CAAC,CAAC,OAAO,EAS3F,SAAgBC,EACf,EACA,EACA,EACC,CACD,IAAMC,EAAOC,EAAM,UACbC,EAAoD,CACzD,OAAQD,EAAM,MAAM,OACpB,OAAQA,EAAM,MAAM,OACpB,QAASA,EAAM,MAAM,GACrB,IAAKA,EAAM,MAAM,GACjB,KAAMN,CACP,EACMQ,EAAoD,CACzD,OAAQ,YAAYH,EAAK,SACzB,OAAQ,gCAAgCA,EAAK,SAC7C,QAAS,2BAA2BA,EAAK,SACzC,IAAK,aAAaA,EAAK,eACvB,KAAM,QAAQA,EAAK,oBACpB,EACMI,EAAyC,CAAC,EAChD,IAAK,IAAMC,IAAQ,CAAC,SAAU,SAAU,UAAW,MAAO,MAAM,EAAY,CAC3E,IAAMC,EAAUC,EAASF,GACpBC,IACL,EAAM,GAAGN,EAAK,GAAGK,KAAU,CAC1B,KAAM,GAAGL,EAAK,GAAGK,IACjB,YAAaG,GAAS,eAAeH,IAASF,EAASE,GACvD,KAAMH,EAAMG,GACZ,SACD,EACD,CAEA,OAAOD,CACR"}
1
+ {"version":3,"file":"agent-tools.mjs","names":["createAgentTools","name","table","masks","listArgsSchema","defaults","tools","verb","handler","handlers","options","listArgs","k","convexPaginationOptions","bindOperationExecutor","createOperationTools","operationToolDialect","selectOperation"],"sources":["../src/agent-tools.ts"],"sourcesContent":["import { k, type KObject, type KType } from './k'\nimport { convexPaginationOptions } from './querying/filters'\n\n/**\n * A framework-agnostic tool record: `args` is a `k` schema, which implements Standard Schema v1\n * (`args['~standard']`) and parses with `args.parse`. For a JSON Schema of the input (ids are strings,\n * `.describe()` texts carry through) call `toJsonSchema(record.args)` from `cvx-kit/json-schema`; for a\n * framework that only takes Zod, `toZod(record.args)` from `cvx-kit/zod`. The kit imports no agent\n * framework.\n */\nexport type AgentToolRecord<Result = unknown, Context = never, Input = never> = {\n\tname: string\n\tdescription: string\n\targs: KType\n\thandler: (ctx: Context, input: Input) => Promise<Result>\n}\n\ntype ToolTable = {\n\treadonly tableName: string\n\treadonly tools: {\n\t\treadonly insert: KType\n\t\treadonly update: KType\n\t\treadonly id: KType\n\t}\n}\n\n/** The `list` tool input: Convex's pagination options under `paginationOpts`. */\nexport type AgentListArgs = KObject<{\n\treadonly paginationOpts: ReturnType<typeof convexPaginationOptions>\n}>\n\ntype ToolHandler<Result> = (ctx: never, input: never) => Promise<Result>\n\nexport type AgentToolHandlers<Result = unknown> = {\n\t/** Mutations: route through command executors — agents get audited commands. */\n\tcreate?: ToolHandler<Result>\n\tupdate?: ToolHandler<Result>\n\tarchive?: ToolHandler<Result>\n\t/** Reads: caller-supplied query handlers (reads do not route through commands). */\n\tget?: ToolHandler<Result>\n\tlist?: ToolHandler<Result>\n}\n\n/**\n * Emits agent tool definitions from the existing table tool masks: args are\n * the masks (`k` schemas; ids are strings in their JSON Schema),\n * names are `<tableName>_<verb>`, and only the kinds you supply handlers for\n * are emitted. Wire mutation handlers to createCrudCommands executors (or\n * your own) so every agent action is an audited command.\n */\nexport function createAgentTools<Table extends ToolTable, Handlers extends AgentToolHandlers>(\n\ttable: Table,\n\thandlers: Handlers,\n\toptions?: { descriptions?: Partial<Record<keyof AgentToolHandlers, string>> },\n) {\n\tconst name = table.tableName\n\tconst masks: Record<keyof AgentToolHandlers, () => KType> = {\n\t\tcreate: () => table.tools.insert,\n\t\tupdate: () => table.tools.update,\n\t\tarchive: () => table.tools.id,\n\t\tget: () => table.tools.id,\n\t\tlist: listArgsSchema,\n\t}\n\tconst defaults: Record<keyof AgentToolHandlers, string> = {\n\t\tcreate: `Create a ${name} record`,\n\t\tupdate: `Update fields of an existing ${name} record`,\n\t\tarchive: `Archive (soft-delete) a ${name} record`,\n\t\tget: `Fetch one ${name} record by id`,\n\t\tlist: `List ${name} records, paginated`,\n\t}\n\tconst tools: Record<string, AgentToolRecord> = {}\n\tfor (const verb of ['create', 'update', 'archive', 'get', 'list'] as const) {\n\t\tconst handler = handlers[verb]\n\t\tif (!handler) continue\n\t\ttools[`${name}_${verb}`] = {\n\t\t\tname: `${name}_${verb}`,\n\t\t\tdescription: options?.descriptions?.[verb] ?? defaults[verb],\n\t\t\targs: masks[verb](),\n\t\t\thandler,\n\t\t}\n\t}\n\t// SAFETY: each emitted key combines this table name with a supplied verb; its handler and schema come from those same inputs.\n\treturn tools as AgentTools<Table, Handlers>\n}\n\nexport type AgentTools<Table extends ToolTable, Handlers extends AgentToolHandlers> = Partial<{\n\t[Verb in keyof Handlers & keyof AgentToolHandlers as `${Table['tableName']}_${Verb}`]: {\n\t\tname: string\n\t\tdescription: string\n\t\targs: Verb extends 'create'\n\t\t\t? Table['tools']['insert']\n\t\t\t: Verb extends 'update'\n\t\t\t\t? Table['tools']['update']\n\t\t\t\t: Verb extends 'list'\n\t\t\t\t\t? AgentListArgs\n\t\t\t\t\t: Table['tools']['id']\n\t\thandler: NonNullable<Handlers[Verb]>\n\t}\n}>\nexport {\n\tselectOperation,\n\tbindOperationExecutor,\n\tcreateOperationTools,\n\toperationToolDialect,\n\ttype SelectedOperation,\n\ttype OperationExecutor,\n\ttype OperationPublicResult,\n\ttype OperationToolJsonSchema,\n\ttype OperationToolConverter,\n\ttype OperationToolDefinition,\n\ttype OperationToolOutcome,\n\ttype OperationTool,\n} from './modules/contracts/exposure'\n\nlet listArgs: AgentListArgs | undefined\n\n/** Built on the first `list` tool, so importing this module builds nothing. */\nfunction listArgsSchema(): AgentListArgs {\n\treturn (listArgs ??= k.object({ paginationOpts: convexPaginationOptions() }))\n}\n"],"mappings":"A,qPAkDA,SAAgBA,EACf,EACA,EACA,EACC,CACD,IAAMC,EAAOC,EAAM,UACbC,EAAsD,CAC3D,WAAcD,EAAM,MAAM,OAC1B,WAAcA,EAAM,MAAM,OAC1B,YAAeA,EAAM,MAAM,GAC3B,QAAWA,EAAM,MAAM,GACvB,KAAME,CACP,EACMC,EAAoD,CACzD,OAAQ,YAAYJ,EAAK,SACzB,OAAQ,gCAAgCA,EAAK,SAC7C,QAAS,2BAA2BA,EAAK,SACzC,IAAK,aAAaA,EAAK,eACvB,KAAM,QAAQA,EAAK,oBACpB,EACMK,EAAyC,CAAC,EAChD,IAAK,IAAMC,IAAQ,CAAC,SAAU,SAAU,UAAW,MAAO,MAAM,EAAY,CAC3E,IAAMC,EAAUC,EAASF,GACpBC,IACL,EAAM,GAAGP,EAAK,GAAGM,KAAU,CAC1B,KAAM,GAAGN,EAAK,GAAGM,IACjB,YAAaG,GAAS,eAAeH,IAASF,EAASE,GACvD,KAAMJ,EAAMI,EAAK,CAAC,EAClB,SACD,EACD,CAEA,OAAOD,CACR,CA+BA,IAAIK,EAGJ,SAASP,GAAgC,CACxC,MAAQ,KAAaQ,EAAE,OAAO,CAAE,eAAgBC,EAAwB,CAAE,CAAC,CAC5E,C"}
package/dist/auth.d.mts CHANGED
@@ -1,10 +1,10 @@
1
+ import { KCustomBuilder } from "./registration.mjs";
2
+ import { ArgumentFailurePolicy } from "./modules/contracts/errors.mjs";
1
3
  import { ErrorFactory } from "./errors.mjs";
2
- import { RLSConfig, Rules } from "./tenancy.mjs";
3
4
  import { SecurityPolicyContext } from "./querying/security.mjs";
4
- import { CustomBuilder } from "convex-helpers/server/zod4";
5
+ import { RLSConfig, Rules } from "./tenancy.mjs";
5
6
  import { ActionBuilder, DefaultFunctionArgs, DocumentByInfo, GenericActionCtx, GenericDataModel, GenericMutationCtx, GenericQueryCtx, GenericTableInfo, IndexNames, IndexRange, IndexRangeBuilder, MutationBuilder, NamedIndex, PaginationOptions, PaginationResult, Query, QueryBuilder, QueryInitializer, TableNamesInDataModel, UserIdentity } from "convex/server";
6
7
  import { Triggers } from "convex-helpers/server/triggers";
7
- //#region src/auth.d.ts
8
8
  /** The default vocabulary; every app can supply its own via the Role generic. */
9
9
  export type DefaultRole = 'reader' | 'writer' | 'admin';
10
10
  export type Actor<Role extends string> = Readonly<{
@@ -129,6 +129,12 @@ export type AuthReadersConfig<DataModel extends GenericDataModel, Role extends s
129
129
  errors?: ErrorFactory;
130
130
  /** Upper bound for include() reads. */
131
131
  maxIncludedQueryRows?: number;
132
+ /**
133
+ * How argument validation failures are thrown by every constructor. `'validation'`
134
+ * (default) throws `KValidationError` (`ConvexError({ code: 'VALIDATION', issues })`);
135
+ * `'declared'` throws `argumentErrors` `INVALID_ARGUMENTS`; a function returns the value to throw.
136
+ */
137
+ argumentFailure?: ArgumentFailurePolicy;
132
138
  /**
133
139
  * Row-level security: tenant isolation (from a table registry) and
134
140
  * role-level rules, applied structurally inside every auth*, role*,
@@ -164,26 +170,27 @@ export type IncludedQuery<Table extends GenericTableInfo> = {
164
170
  * by the same maxRows policy as execute(). Under row-level security a
165
171
  * page may be shorter than numItems (rejected rows are filtered after
166
172
  * pagination); cursors remain correct. Pair with paginated(dto) from
167
- * cvx-kit/zod-table for the boundary schemas.
173
+ * cvx-kit/table for the boundary schemas.
168
174
  */
169
175
  paginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>;
170
176
  paginate<Item>(opts: PaginationOptions, transform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>): Promise<PaginationResult<Item>>;
171
177
  };
172
178
  export type Include = <Table extends GenericTableInfo>(query: QueryInitializer<Table>) => IncludedQuery<Table>;
173
179
  /**
174
- * Keep native contexts symbolic in published declarations. Inferred spreads
180
+ * The auth-aware constructors, registered through `k` schemas and native validators
181
+ * (src/registration.ts). Keep native contexts symbolic in published declarations: inferred spreads
175
182
  * copy build-time Convex methods and override the consumer's native context.
176
183
  */
177
184
  export type AuthFunctions<DataModel extends GenericDataModel, Role extends string = DefaultRole> = {
178
185
  include: Include;
179
186
  authenticatedUser: (ctx: AnyAuthContext<DataModel>) => Promise<AuthBundle<Role>>;
180
- authQuery: CustomBuilder<'query', {}, GenericQueryCtx<DataModel> & AuthBundle<Role> & {
187
+ authQuery: KCustomBuilder<'query', {}, GenericQueryCtx<DataModel> & AuthBundle<Role> & {
181
188
  include: Include;
182
189
  }, {}, GenericQueryCtx<DataModel>, 'public', object>;
183
- authMutation: CustomBuilder<'mutation', {}, GenericMutationCtx<DataModel> & AuthBundle<Role> & {
190
+ authMutation: KCustomBuilder<'mutation', {}, GenericMutationCtx<DataModel> & AuthBundle<Role> & {
184
191
  include: Include;
185
192
  }, {}, GenericMutationCtx<DataModel>, 'public', object>;
186
- authAction: CustomBuilder<'action', {}, GenericActionCtx<DataModel> & AuthBundle<Role>, {}, GenericActionCtx<DataModel>, 'public', object>;
193
+ authAction: KCustomBuilder<'action', {}, GenericActionCtx<DataModel> & AuthBundle<Role>, {}, GenericActionCtx<DataModel>, 'public', object>;
187
194
  roleQuery: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authQuery'];
188
195
  roleMutation: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authMutation'];
189
196
  roleAction: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authAction'];
@@ -198,20 +205,20 @@ export type AuthFunctions<DataModel extends GenericDataModel, Role extends strin
198
205
  serviceQuery: <Extra extends Record<string, unknown> = {}>(principal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>) => ServiceQuery<DataModel, Role, Extra>;
199
206
  /** Internal mutation running as a service principal: triggers first, then the secured writer. */
200
207
  serviceMutation: <Extra extends Record<string, unknown> = {}>(principal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>) => ServiceMutation<DataModel, Role, Extra>;
201
- systemQuery: CustomBuilder<'query', {}, GenericQueryCtx<DataModel> & {
208
+ systemQuery: KCustomBuilder<'query', {}, GenericQueryCtx<DataModel> & {
202
209
  include: Include;
203
210
  }, {}, GenericQueryCtx<DataModel>, 'internal', object>;
204
- systemMutation: CustomBuilder<'mutation', {}, GenericMutationCtx<DataModel> & {
211
+ systemMutation: KCustomBuilder<'mutation', {}, GenericMutationCtx<DataModel> & {
205
212
  include: Include;
206
213
  }, {}, GenericMutationCtx<DataModel>, 'internal', object>;
207
- systemAction: CustomBuilder<'action', {}, GenericActionCtx<DataModel>, {}, GenericActionCtx<DataModel>, 'internal', object>;
214
+ systemAction: KCustomBuilder<'action', {}, GenericActionCtx<DataModel>, {}, GenericActionCtx<DataModel>, 'internal', object>;
208
215
  };
209
216
  /** The read-only constructors: everything AuthFunctions has except mutations. */
210
217
  export type AuthReaders<DataModel extends GenericDataModel, Role extends string = DefaultRole> = Omit<AuthFunctions<DataModel, Role>, `${string}Mutation`>;
211
- export type ServiceQuery<DataModel extends GenericDataModel, Role extends string, Extra extends Record<string, unknown> = {}> = CustomBuilder<'query', {}, GenericQueryCtx<DataModel> & AuthBundle<Role> & Extra & {
218
+ export type ServiceQuery<DataModel extends GenericDataModel, Role extends string, Extra extends Record<string, unknown> = {}> = KCustomBuilder<'query', {}, GenericQueryCtx<DataModel> & AuthBundle<Role> & Extra & {
212
219
  include: Include;
213
220
  }, {}, GenericQueryCtx<DataModel>, 'internal', object>;
214
- export type ServiceMutation<DataModel extends GenericDataModel, Role extends string, Extra extends Record<string, unknown> = {}> = CustomBuilder<'mutation', {}, GenericMutationCtx<DataModel> & AuthBundle<Role> & Extra & {
221
+ export type ServiceMutation<DataModel extends GenericDataModel, Role extends string, Extra extends Record<string, unknown> = {}> = KCustomBuilder<'mutation', {}, GenericMutationCtx<DataModel> & AuthBundle<Role> & Extra & {
215
222
  include: Include;
216
223
  }, {}, GenericMutationCtx<DataModel>, 'internal', object>;
217
224
  /** Builds an include() that selects the first matching indexed query and bounds the read. */
@@ -236,6 +243,5 @@ export declare function createAuthFunctions<DataModel extends GenericDataModel,
236
243
  * trigger registry or the domains it pulls in.
237
244
  */
238
245
  export declare function createAuthReaders<DataModel extends GenericDataModel, const Role extends string = DefaultRole>(config: AuthReadersConfig<DataModel, Role>): AuthReaders<DataModel, Role>;
239
- //#endregion
240
246
  export type { SecurityPolicyContext };
241
247
  //# sourceMappingURL=auth.d.mts.map
package/dist/auth.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{rawFunctionArgs as e,zCustomAction as t,zCustomMutation as n,zCustomQuery as r}from"./zod-registration.mjs";import{defaultErrors as i}from"./errors.mjs";import{registerQueryReader as a,suppliedPolicyRules as o}from"./querying/security.mjs";import{composeRules as s,createTenantRules as c,wrapDatabaseReader as l,wrapDatabaseWriter as u}from"./tenancy.mjs";import{z as d}from"zod";function f(e){let t=e?.trim().toLowerCase();return t===`member`?`writer`:t===`reader`||t===`writer`||t===`admin`?t:null}function p(e){let t=e?.errors??i,n=e?.maxRows??100;function r(e,i){async function a(r,a){if(!Number.isSafeInteger(r)||r<1||r>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A bounded query limit must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).take(r);return a?a(o):o}async function o(r,a){if(!Number.isSafeInteger(r.numItems)||r.numItems<1||r.numItems>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A page size must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).paginate(r);return a?{...o,page:await a(o.page)}:o}return{when:(t,n)=>i||t==null?r(e,i):r(e,n(e,t)),matching:(t,n,a=!0)=>i||!a?r(e,i):r(e,e.withIndex(t,n)),otherwise:t=>i??t(e),resolve:()=>i??e.fullTableScan(),execute:a,paginate:o}}return e=>r(e)}function m(e){let t=g(e),{include:r,secureWriter:i,servicePrincipal:a,requireRole:o}=t,s=e.triggers,c=s?e=>s.wrapDB(e):e.wrapDB??(e=>e);async function l(e){let n=await t.authenticatedUser(e);return{ctx:{...i(c(e),n),include:r,...n},args:{}}}function u(t){return n(e.internalMutation,{args:{},input:async e=>{let n=await a(t,e);return{ctx:{...i(c(e),n),...n,include:r},args:{}}}})}function d(...t){return n(e.mutation,{args:{},input:async e=>{let n=await l(e);return o(n.ctx.actor.role,t),n}})}return{...t.readers,roleMutation:d,authMutation:n(e.mutation,{args:{},input:l}),adminMutation:d(...e.adminRoles),serviceMutation:u,systemMutation:n(e.internalMutation,{args:{},input:async e=>({ctx:{...c(e),include:r},args:{}})})}}function h(e){return g(e).readers}function g(n){let d=n.errors??i,f=p({errors:d,maxRows:n.maxIncludedQueryRows});async function m(e){let t=await e.auth.getUserIdentity(),r=t?await n.getAuthUser(e,t):null;if(!t||!r)return d.throw({code:`UNAUTHENTICATED`});let i,a;if(n.resolveOrganization){let o=null;try{o=await n.resolveOrganization({ctx:e,identity:t,user:r})}catch{}if(!o)return d.throw({code:`FORBIDDEN`});i=o.organizationId,a=o.roleSlug}else{let e=v.parse(t),n=e.organization?.organizationId??e.org_id;if(!n)return d.throw({code:`UNAUTHENTICATED`});i=n,a=e.organization?.role??e.role}let o=n.mapRole(a);if(!o)return d.throw({code:`FORBIDDEN`});let s={identity:t,user:Object.freeze({id:r.id}),org:Object.freeze({organizationId:i,role:o}),role:o,actor:Object.freeze({userId:r.id,organizationId:i,role:o})};return Object.freeze({...s,tenant:n.security?.tenancy?.resolve?.(s)??i})}let h=n.security?{defaultPolicy:n.security.defaultPolicy??(n.security.tenancy?`deny`:`allow`)}:void 0;function g(e){let t=n.security;if(!t)return;let r=[];return t.tenancy&&r.push(c(e.tenant,t.tenancy.tables)),t.rules&&r.push(t.rules(e)),r.length===1?r[0]:s(...r)}function y(e,t,n=`authenticated`){let r=g(t),i=h?.defaultPolicy??`allow`,s=r?l({db:e.db},e.db,o(e.db,r,i),h):e.db;return{...e,db:a(e.db,s,{scope:{mode:n,principal:t.user.id,organization:t.org.organizationId,tenant:t.tenant,role:t.role},rules:r??{},defaultPolicy:i})}}function b(e,t){let n=g(t);return n?{...e,db:u({db:e.db},e.db,o(e.db,n,h?.defaultPolicy??`allow`),h)}:e}async function x(e,t){if(!n.verifyMembership)return null;try{let r=await n.verifyMembership({userId:e,organizationId:t});if(r&&r.organizationId===t)return r}catch{}return d.throw({code:`FORBIDDEN`})}function S(e,t){if(!t.includes(e))return d.throw({code:`FORBIDDEN`})}async function C(e){let t=await m(e);return{ctx:{...y(e,t),include:f,...t},args:{}}}async function w(e){let t=await m(e),r=await x(t.user.id,t.org.organizationId);if(!r)return{ctx:{...e,...t},args:{}};let i=n.mapRole(r.roleSlug);if(!i)return d.throw({code:`FORBIDDEN`});let a={identity:t.identity,user:t.user,org:Object.freeze({organizationId:r.organizationId,role:i}),role:i,actor:Object.freeze({userId:t.user.id,organizationId:r.organizationId,role:i})};return{ctx:{...e,...a,tenant:n.security?.tenancy?.resolve?.(a)??r.organizationId},args:{}}}async function T(t,n){let r=await t(n,e(n));if(!_.safeParse(r).success)throw Error(`A service principal must be an AuthBundle with user.id and tenant`);let i=Object.keys(r).filter(e=>e in n);if(i.length>0)throw Error(`A service principal cannot override native context fields: ${i.join(`, `)}`);return r}function E(e){return r(n.internalQuery,{args:{},input:async t=>{let n=await T(e,t);return{ctx:{...y(t,n,`trusted`),...n,include:f},args:{}}}})}function D(...e){return r(n.query,{args:{},input:async t=>{let n=await C(t);return S(n.ctx.actor.role,e),n}})}function O(...e){return t(n.action,{args:{},input:async t=>{let n=await w(t);return S(n.ctx.actor.role,e),n}})}return{readers:{include:f,authenticatedUser:m,roleQuery:D,roleAction:O,authQuery:r(n.query,{args:{},input:C}),authAction:t(n.action,{args:{},input:w}),adminQuery:D(...n.adminRoles),adminAction:O(...n.adminRoles),serviceQuery:E,systemQuery:r(n.internalQuery,{args:{},input:async e=>({ctx:{...e,include:f,db:a(e.db,e.db,{scope:{mode:`system`,principal:null,organization:null,tenant:null,role:null},rules:{},defaultPolicy:`allow`})},args:{}})}),systemAction:t(n.internalAction,{args:{},input:async e=>({ctx:e,args:{}})})},include:f,authenticatedUser:m,secureWriter:b,servicePrincipal:T,requireRole:S}}const _=d.object({user:d.object({id:d.string()}),tenant:d.string()}),v=d.object({organization:d.object({organizationId:d.string().optional().catch(void 0),role:d.string().optional().catch(void 0)}).optional().catch(void 0),org_id:d.string().optional().catch(void 0),role:d.string().optional().catch(void 0)});export{m as createAuthFunctions,h as createAuthReaders,p as createInclude,f as defaultRoleMap};
1
+ import{kCustomFunctions as e,rawFunctionArgs as t}from"./registration.mjs";import{k as n}from"./k/index.mjs";import{memoize as r}from"./modules/contracts/lazy.mjs";import{defaultErrors as i}from"./errors.mjs";import{registerQueryReader as a,suppliedPolicyRules as o}from"./querying/security.mjs";import{composeRules as s,createTenantRules as c,wrapDatabaseReader as l,wrapDatabaseWriter as u}from"./tenancy.mjs";function d(e){let t=e?.trim().toLowerCase();return t===`member`?`writer`:t===`reader`||t===`writer`||t===`admin`?t:null}function f(e){let t=e?.errors??i,n=e?.maxRows??100;function r(e,i){async function a(r,a){if(!Number.isSafeInteger(r)||r<1||r>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A bounded query limit must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).take(r);return a?a(o):o}async function o(r,a){if(!Number.isSafeInteger(r.numItems)||r.numItems<1||r.numItems>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A page size must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).paginate(r);return a?{...o,page:await a(o.page)}:o}return{when:(t,n)=>i||t==null?r(e,i):r(e,n(e,t)),matching:(t,n,a=!0)=>i||!a?r(e,i):r(e,e.withIndex(t,n)),otherwise:t=>i??t(e),resolve:()=>i??e.fullTableScan(),execute:a,paginate:o}}return e=>r(e)}function p(e){let t=_(e),n=g(e,t),{kCustomMutation:r}=t.builders;function i(t){return r(e.internalMutation,{args:{},input:n.serviceMutationInput(t)})}function a(...t){return r(e.mutation,{args:{},input:n.roleMutationInput(t)})}return{...h(e,t),roleMutation:a,authMutation:r(e.mutation,{args:{},input:n.mutationInput}),adminMutation:a(...e.adminRoles),serviceMutation:i,systemMutation:r(e.internalMutation,{args:{},input:n.systemMutationInput})}}function m(e){return h(e,_(e))}function h(e,t){let{kCustomQuery:n,kCustomAction:r}=t.builders;function i(r){return n(e.internalQuery,{args:{},input:t.serviceQueryInput(r)})}function a(...r){return n(e.query,{args:{},input:t.roleQueryInput(r)})}function o(...n){return r(e.action,{args:{},input:t.roleActionInput(n)})}return{include:t.include,authenticatedUser:t.authenticatedUser,roleQuery:a,roleAction:o,authQuery:n(e.query,{args:{},input:t.queryInput}),authAction:r(e.action,{args:{},input:t.actionInput}),adminQuery:a(...e.adminRoles),adminAction:o(...e.adminRoles),serviceQuery:i,systemQuery:n(e.internalQuery,{args:{},input:t.systemQueryInput}),systemAction:r(e.internalAction,{args:{},input:t.systemActionInput})}}function g(e,t){let{include:n,secureWriter:r,servicePrincipal:i,requireRole:a}=t,o=e.triggers,s=o?e=>o.wrapDB(e):e.wrapDB??(e=>e);async function c(e){let i=await t.authenticatedUser(e);return{ctx:{...r(s(e),i),include:n,...i},args:{}}}return{mutationInput:c,serviceMutationInput:e=>async t=>{let a=await i(e,t);return{ctx:{...r(s(t),a),...a,include:n},args:{}}},roleMutationInput:e=>async t=>{let n=await c(t);return a(n.ctx.actor.role,e),n},systemMutationInput:async e=>({ctx:{...s(e),include:n},args:{}})}}function _(n){let r=n.errors??i,d=e({argumentFailure:n.argumentFailure}),p=f({errors:r,maxRows:n.maxIncludedQueryRows});async function m(e){let t=await e.auth.getUserIdentity(),i=t?await n.getAuthUser(e,t):null;if(!t||!i)return r.throw({code:`UNAUTHENTICATED`});let a,o;if(n.resolveOrganization){let s=null;try{s=await n.resolveOrganization({ctx:e,identity:t,user:i})}catch{}if(!s)return r.throw({code:`FORBIDDEN`});a=s.organizationId,o=s.roleSlug}else{let e=y(t);if(!e.organizationId)return r.throw({code:`UNAUTHENTICATED`});a=e.organizationId,o=e.role}let s=n.mapRole(o);if(!s)return r.throw({code:`FORBIDDEN`});let c={identity:t,user:Object.freeze({id:i.id}),org:Object.freeze({organizationId:a,role:s}),role:s,actor:Object.freeze({userId:i.id,organizationId:a,role:s})};return Object.freeze({...c,tenant:n.security?.tenancy?.resolve?.(c)??a})}let h=n.security?{defaultPolicy:n.security.defaultPolicy??(n.security.tenancy?`deny`:`allow`)}:void 0;function g(e){let t=n.security;if(!t)return;let r=[];return t.tenancy&&r.push(c(e.tenant,t.tenancy.tables)),t.rules&&r.push(t.rules(e)),r.length===1?r[0]:s(...r)}function _(e,t,n=`authenticated`){let r=g(t),i=h?.defaultPolicy??`allow`,s=r?l({db:e.db},e.db,o(e.db,r,i),h):e.db;return{...e,db:a(e.db,s,{scope:{mode:n,principal:t.user.id,organization:t.org.organizationId,tenant:t.tenant,role:t.role},rules:r??{},defaultPolicy:i})}}function b(e,t){let n=g(t);return n?{...e,db:u({db:e.db},e.db,o(e.db,n,h?.defaultPolicy??`allow`),h)}:e}async function x(e,t){if(!n.verifyMembership)return null;try{let r=await n.verifyMembership({userId:e,organizationId:t});if(r&&r.organizationId===t)return r}catch{}return r.throw({code:`FORBIDDEN`})}function S(e,t){if(!t.includes(e))return r.throw({code:`FORBIDDEN`})}async function C(e){let t=await m(e);return{ctx:{..._(e,t),include:p,...t},args:{}}}async function w(e){let t=await m(e),i=await x(t.user.id,t.org.organizationId);if(!i)return{ctx:{...e,...t},args:{}};let a=n.mapRole(i.roleSlug);if(!a)return r.throw({code:`FORBIDDEN`});let o={identity:t.identity,user:t.user,org:Object.freeze({organizationId:i.organizationId,role:a}),role:a,actor:Object.freeze({userId:t.user.id,organizationId:i.organizationId,role:a})};return{ctx:{...e,...o,tenant:n.security?.tenancy?.resolve?.(o)??i.organizationId},args:{}}}async function T(e,n){let r=await e(n,t(n));if(!v().safeParse(r).success)throw Error(`A service principal must be an AuthBundle with user.id and tenant`);let i=Object.keys(r).filter(e=>e in n);if(i.length>0)throw Error(`A service principal cannot override native context fields: ${i.join(`, `)}`);return r}return{builders:d,include:p,authenticatedUser:m,secureWriter:b,servicePrincipal:T,requireRole:S,queryInput:C,actionInput:w,serviceQueryInput:e=>async t=>{let n=await T(e,t);return{ctx:{..._(t,n,`trusted`),...n,include:p},args:{}}},roleQueryInput:e=>async t=>{let n=await C(t);return S(n.ctx.actor.role,e),n},roleActionInput:e=>async t=>{let n=await w(t);return S(n.ctx.actor.role,e),n},systemQueryInput:async e=>({ctx:{...e,include:p,db:a(e.db,e.db,{scope:{mode:`system`,principal:null,organization:null,tenant:null,role:null},rules:{},defaultPolicy:`allow`})},args:{}}),systemActionInput:async e=>({ctx:e,args:{}})}}const v=r(()=>n.object({user:n.object({id:n.string()}).strip(),tenant:n.string()}).strip());function y(e){let t=x(e.organization);return{organizationId:b(t?.organizationId)??b(e.org_id),role:b(t?.role)??b(e.role)}}function b(e){return typeof e==`string`?e:void 0}function x(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}export{p as createAuthFunctions,m as createAuthReaders,f as createInclude,d as defaultRoleMap};
2
2
  //# sourceMappingURL=auth.mjs.map