cvx-kit 0.2.0 → 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 (372) hide show
  1. package/README.md +556 -99
  2. package/dist/agent-tools.d.mts +39 -26
  3. package/dist/agent-tools.mjs +1 -1
  4. package/dist/agent-tools.mjs.map +1 -1
  5. package/dist/auth.d.mts +120 -308
  6. package/dist/auth.mjs +1 -1
  7. package/dist/auth.mjs.map +1 -1
  8. package/dist/components/approvals/_generated/api.d.mts +7 -9
  9. package/dist/components/approvals/_generated/api.mjs.map +1 -1
  10. package/dist/components/approvals/_generated/component.d.mts +1 -4
  11. package/dist/components/approvals/_generated/dataModel.d.mts +5 -8
  12. package/dist/components/approvals/_generated/server.d.mts +12 -15
  13. package/dist/components/approvals/_generated/server.mjs.map +1 -1
  14. package/dist/components/approvals/audit.d.mts +8 -9
  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 +11 -12
  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 +30 -31
  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 +13 -17
  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 +3 -4
  28. package/dist/components/approvals/functions.mjs +1 -1
  29. package/dist/components/approvals/functions.mjs.map +1 -1
  30. package/dist/components/approvals/health.d.mts +2 -3
  31. package/dist/components/approvals/health.mjs.map +1 -1
  32. package/dist/components/approvals/requests.d.mts +114 -131
  33. package/dist/components/approvals/requests.mjs +1 -1
  34. package/dist/components/approvals/requests.mjs.map +1 -1
  35. package/dist/components/approvals/schema.d.ts +106 -315
  36. package/dist/components/approvals/schema.js +1 -1
  37. package/dist/components/approvals/validators.d.mts +323 -395
  38. package/dist/components/approvals/validators.mjs +1 -1
  39. package/dist/components/approvals/validators.mjs.map +1 -1
  40. package/dist/components/approvals/workflow.d.mts +4 -5
  41. package/dist/components/approvals/workflow.mjs +1 -1
  42. package/dist/components/approvals/workflow.mjs.map +1 -1
  43. package/dist/components/approvals/workflow_steps.d.mts +16 -17
  44. package/dist/components/approvals/workflow_steps.mjs +1 -1
  45. package/dist/components/approvals/workflow_steps.mjs.map +1 -1
  46. package/dist/components/foundation/_generated/api.d.mts +6 -8
  47. package/dist/components/foundation/_generated/api.mjs.map +1 -1
  48. package/dist/components/foundation/_generated/component.d.mts +1 -4
  49. package/dist/components/foundation/_generated/dataModel.d.mts +5 -8
  50. package/dist/components/foundation/_generated/server.d.mts +12 -15
  51. package/dist/components/foundation/_generated/server.mjs.map +1 -1
  52. package/dist/components/foundation/client.d.mts +45 -38
  53. package/dist/components/foundation/client.mjs +1 -1
  54. package/dist/components/foundation/client.mjs.map +1 -1
  55. package/dist/components/foundation/convex.config.d.mts +0 -2
  56. package/dist/components/foundation/convex.config.mjs.map +1 -1
  57. package/dist/components/foundation/functions.d.mts +2 -3
  58. package/dist/components/foundation/functions.mjs.map +1 -1
  59. package/dist/components/foundation/modules/command/command.d.mts +65 -17
  60. package/dist/components/foundation/modules/command/command.mjs +1 -1
  61. package/dist/components/foundation/modules/command/command.mjs.map +1 -1
  62. package/dist/components/foundation/modules/command/lifecycle.d.mts +78 -0
  63. package/dist/components/foundation/modules/command/lifecycle.mjs +2 -0
  64. package/dist/components/foundation/modules/command/lifecycle.mjs.map +1 -0
  65. package/dist/components/foundation/modules/observability/observability.d.mts +13 -6
  66. package/dist/components/foundation/modules/observability/observability.mjs +1 -1
  67. package/dist/components/foundation/modules/observability/observability.mjs.map +1 -1
  68. package/dist/components/foundation/modules/query/query.d.mts +11 -12
  69. package/dist/components/foundation/modules/query/query.mjs +1 -1
  70. package/dist/components/foundation/modules/query/query.mjs.map +1 -1
  71. package/dist/components/foundation/operation.d.mts +72 -0
  72. package/dist/components/foundation/operation.mjs +2 -0
  73. package/dist/components/foundation/operation.mjs.map +1 -0
  74. package/dist/components/foundation/result.d.mts +7 -8
  75. package/dist/components/foundation/result.mjs.map +1 -1
  76. package/dist/components/foundation/schema.d.ts +0 -2
  77. package/dist/components/foundation/telemetry.d.mts +2 -3
  78. package/dist/components/foundation/telemetry.mjs +1 -1
  79. package/dist/components/foundation/telemetry.mjs.map +1 -1
  80. package/dist/contracts.d.mts +5 -0
  81. package/dist/contracts.mjs +1 -0
  82. package/dist/crud.d.mts +185 -27
  83. package/dist/crud.mjs +1 -1
  84. package/dist/crud.mjs.map +1 -1
  85. package/dist/effect.d.mts +16 -0
  86. package/dist/effect.mjs +1 -0
  87. package/dist/errors.d.mts +6 -6
  88. package/dist/errors.mjs +1 -1
  89. package/dist/errors.mjs.map +1 -1
  90. package/dist/filters.d.mts +4 -0
  91. package/dist/filters.mjs +1 -0
  92. package/dist/idempotency.d.mts +2 -0
  93. package/dist/idempotency.mjs +1 -0
  94. package/dist/index.d.mts +14 -7
  95. package/dist/index.mjs +1 -1
  96. package/dist/json-schema.d.mts +40 -0
  97. package/dist/json-schema.mjs +2 -0
  98. package/dist/json-schema.mjs.map +1 -0
  99. package/dist/k/compile.d.mts +17 -0
  100. package/dist/k/compile.mjs +2 -0
  101. package/dist/k/compile.mjs.map +1 -0
  102. package/dist/k/dates.d.mts +23 -0
  103. package/dist/k/dates.mjs +2 -0
  104. package/dist/k/dates.mjs.map +1 -0
  105. package/dist/k/formats.d.mts +24 -0
  106. package/dist/k/formats.mjs +2 -0
  107. package/dist/k/formats.mjs.map +1 -0
  108. package/dist/k/index.d.mts +32 -0
  109. package/dist/k/index.mjs +2 -0
  110. package/dist/k/index.mjs.map +1 -0
  111. package/dist/k/issues.d.mts +31 -0
  112. package/dist/k/issues.mjs +2 -0
  113. package/dist/k/issues.mjs.map +1 -0
  114. package/dist/k/kinds.d.mts +81 -0
  115. package/dist/k/kinds.mjs +2 -0
  116. package/dist/k/kinds.mjs.map +1 -0
  117. package/dist/k/object.d.mts +43 -0
  118. package/dist/k/object.mjs +2 -0
  119. package/dist/k/object.mjs.map +1 -0
  120. package/dist/k/parse.d.mts +29 -0
  121. package/dist/k/parse.mjs +2 -0
  122. package/dist/k/parse.mjs.map +1 -0
  123. package/dist/k/schema.d.mts +100 -0
  124. package/dist/k/schema.mjs +2 -0
  125. package/dist/k/schema.mjs.map +1 -0
  126. package/dist/k/standard.d.mts +8 -0
  127. package/dist/k/standard.mjs +2 -0
  128. package/dist/k/standard.mjs.map +1 -0
  129. package/dist/k/types.d.mts +64 -0
  130. package/dist/k/types.mjs +1 -0
  131. package/dist/k.d.mts +8 -0
  132. package/dist/k.mjs +1 -0
  133. package/dist/middleware.d.mts +8 -11
  134. package/dist/middleware.mjs +1 -1
  135. package/dist/middleware.mjs.map +1 -1
  136. package/dist/modules/contracts/binding.d.mts +23 -0
  137. package/dist/modules/contracts/binding.mjs +2 -0
  138. package/dist/modules/contracts/binding.mjs.map +1 -0
  139. package/dist/modules/contracts/contract.d.mts +67 -0
  140. package/dist/modules/contracts/contract.mjs +2 -0
  141. package/dist/modules/contracts/contract.mjs.map +1 -0
  142. package/dist/modules/contracts/convex.d.mts +18 -0
  143. package/dist/modules/contracts/convex.mjs +2 -0
  144. package/dist/modules/contracts/convex.mjs.map +1 -0
  145. package/dist/modules/contracts/domain.d.mts +62 -0
  146. package/dist/modules/contracts/domain.mjs +2 -0
  147. package/dist/modules/contracts/domain.mjs.map +1 -0
  148. package/dist/modules/contracts/errors.d.mts +737 -0
  149. package/dist/modules/contracts/errors.mjs +2 -0
  150. package/dist/modules/contracts/errors.mjs.map +1 -0
  151. package/dist/modules/contracts/exposure.d.mts +103 -0
  152. package/dist/modules/contracts/exposure.mjs +2 -0
  153. package/dist/modules/contracts/exposure.mjs.map +1 -0
  154. package/dist/modules/contracts/idempotency.d.mts +85 -0
  155. package/dist/modules/contracts/idempotency.mjs +2 -0
  156. package/dist/modules/contracts/idempotency.mjs.map +1 -0
  157. package/dist/modules/contracts/lazy.d.mts +6 -0
  158. package/dist/modules/contracts/lazy.mjs +2 -0
  159. package/dist/modules/contracts/lazy.mjs.map +1 -0
  160. package/dist/modules/contracts/standard.d.mts +17 -0
  161. package/dist/modules/contracts/standard.mjs +2 -0
  162. package/dist/modules/contracts/standard.mjs.map +1 -0
  163. package/dist/modules/contracts/workflow.d.mts +165 -0
  164. package/dist/modules/contracts/workflow.mjs +2 -0
  165. package/dist/modules/contracts/workflow.mjs.map +1 -0
  166. package/dist/modules/effect/action.d.mts +63 -0
  167. package/dist/modules/effect/action.mjs +2 -0
  168. package/dist/modules/effect/action.mjs.map +1 -0
  169. package/dist/modules/effect/agent-tools.d.mts +2 -0
  170. package/dist/modules/effect/agent-tools.mjs +1 -0
  171. package/dist/modules/effect/api-runtime.d.mts +36 -0
  172. package/dist/modules/effect/api-runtime.mjs +2 -0
  173. package/dist/modules/effect/api-runtime.mjs.map +1 -0
  174. package/dist/modules/effect/api.d.mts +46 -0
  175. package/dist/modules/effect/api.mjs +2 -0
  176. package/dist/modules/effect/api.mjs.map +1 -0
  177. package/dist/modules/effect/auth.d.mts +46 -0
  178. package/dist/modules/effect/auth.mjs +2 -0
  179. package/dist/modules/effect/auth.mjs.map +1 -0
  180. package/dist/modules/effect/client.d.mts +15 -0
  181. package/dist/modules/effect/client.mjs +1 -0
  182. package/dist/modules/effect/command.d.mts +108 -0
  183. package/dist/modules/effect/command.mjs +2 -0
  184. package/dist/modules/effect/command.mjs.map +1 -0
  185. package/dist/modules/effect/crud.d.mts +885 -0
  186. package/dist/modules/effect/crud.mjs +2 -0
  187. package/dist/modules/effect/crud.mjs.map +1 -0
  188. package/dist/modules/effect/domain.d.mts +82 -0
  189. package/dist/modules/effect/domain.mjs +2 -0
  190. package/dist/modules/effect/domain.mjs.map +1 -0
  191. package/dist/modules/effect/errors.d.mts +13 -0
  192. package/dist/modules/effect/errors.mjs +2 -0
  193. package/dist/modules/effect/errors.mjs.map +1 -0
  194. package/dist/modules/effect/failure-audit.d.mts +48 -0
  195. package/dist/modules/effect/failure-audit.mjs +2 -0
  196. package/dist/modules/effect/failure-audit.mjs.map +1 -0
  197. package/dist/modules/effect/failures.d.mts +21 -0
  198. package/dist/modules/effect/failures.mjs +2 -0
  199. package/dist/modules/effect/failures.mjs.map +1 -0
  200. package/dist/modules/effect/foundation.d.mts +23 -0
  201. package/dist/modules/effect/foundation.mjs +2 -0
  202. package/dist/modules/effect/foundation.mjs.map +1 -0
  203. package/dist/modules/effect/idempotency.d.mts +29 -0
  204. package/dist/modules/effect/idempotency.mjs +2 -0
  205. package/dist/modules/effect/idempotency.mjs.map +1 -0
  206. package/dist/modules/effect/input.d.mts +10 -0
  207. package/dist/modules/effect/input.mjs +2 -0
  208. package/dist/modules/effect/input.mjs.map +1 -0
  209. package/dist/modules/effect/normalize.d.mts +7 -0
  210. package/dist/modules/effect/normalize.mjs +2 -0
  211. package/dist/modules/effect/normalize.mjs.map +1 -0
  212. package/dist/modules/effect/operation.d.mts +148 -0
  213. package/dist/modules/effect/operation.mjs +2 -0
  214. package/dist/modules/effect/operation.mjs.map +1 -0
  215. package/dist/modules/effect/query.d.mts +90 -0
  216. package/dist/modules/effect/query.mjs +2 -0
  217. package/dist/modules/effect/query.mjs.map +1 -0
  218. package/dist/modules/effect/schema.d.mts +30 -0
  219. package/dist/modules/effect/schema.mjs +2 -0
  220. package/dist/modules/effect/schema.mjs.map +1 -0
  221. package/dist/modules/effect/scope.d.mts +25 -0
  222. package/dist/modules/effect/scope.mjs +2 -0
  223. package/dist/modules/effect/scope.mjs.map +1 -0
  224. package/dist/modules/effect/workflow.d.mts +75 -0
  225. package/dist/modules/effect/workflow.mjs +2 -0
  226. package/dist/modules/effect/workflow.mjs.map +1 -0
  227. package/dist/modules/foundation/foundation.d.mts +108 -0
  228. package/dist/modules/foundation/foundation.mjs +2 -0
  229. package/dist/modules/foundation/foundation.mjs.map +1 -0
  230. package/dist/modules/foundation/operation.d.mts +139 -0
  231. package/dist/modules/foundation/operation.mjs +2 -0
  232. package/dist/modules/foundation/operation.mjs.map +1 -0
  233. package/dist/namespace.d.mts +104 -0
  234. package/dist/namespace.mjs +2 -0
  235. package/dist/namespace.mjs.map +1 -0
  236. package/dist/oxlint/architecture.d.mts +23 -0
  237. package/dist/oxlint/architecture.mjs +2 -0
  238. package/dist/oxlint/architecture.mjs.map +1 -0
  239. package/dist/oxlint/ast.d.mts +51 -0
  240. package/dist/oxlint/ast.mjs +2 -0
  241. package/dist/oxlint/ast.mjs.map +1 -0
  242. package/dist/oxlint/components.d.mts +4 -0
  243. package/dist/oxlint/components.mjs +2 -0
  244. package/dist/oxlint/components.mjs.map +1 -0
  245. package/dist/oxlint/ownership.d.mts +59 -0
  246. package/dist/oxlint/ownership.mjs +2 -0
  247. package/dist/oxlint/ownership.mjs.map +1 -0
  248. package/dist/oxlint/reserved-files.d.mts +4 -0
  249. package/dist/oxlint/reserved-files.mjs +2 -0
  250. package/dist/oxlint/reserved-files.mjs.map +1 -0
  251. package/dist/oxlint.d.mts +9 -0
  252. package/dist/oxlint.mjs +2 -0
  253. package/dist/oxlint.mjs.map +1 -0
  254. package/dist/querying/cursors.d.mts +94 -0
  255. package/dist/querying/cursors.mjs +2 -0
  256. package/dist/querying/cursors.mjs.map +1 -0
  257. package/dist/querying/execution.d.mts +40 -0
  258. package/dist/querying/execution.mjs +2 -0
  259. package/dist/querying/execution.mjs.map +1 -0
  260. package/dist/querying/failures.d.mts +11 -0
  261. package/dist/querying/failures.mjs +2 -0
  262. package/dist/querying/failures.mjs.map +1 -0
  263. package/dist/querying/filter-boundary.d.mts +25 -0
  264. package/dist/querying/filter-boundary.mjs +2 -0
  265. package/dist/querying/filter-boundary.mjs.map +1 -0
  266. package/dist/querying/filters.d.mts +180 -0
  267. package/dist/querying/filters.mjs +2 -0
  268. package/dist/querying/filters.mjs.map +1 -0
  269. package/dist/querying/planner.d.mts +61 -0
  270. package/dist/querying/planner.mjs +2 -0
  271. package/dist/querying/planner.mjs.map +1 -0
  272. package/dist/querying/relationships.d.mts +58 -0
  273. package/dist/querying/relationships.mjs +2 -0
  274. package/dist/querying/relationships.mjs.map +1 -0
  275. package/dist/querying/search.d.mts +69 -0
  276. package/dist/querying/search.mjs +2 -0
  277. package/dist/querying/search.mjs.map +1 -0
  278. package/dist/querying/security.d.mts +123 -0
  279. package/dist/querying/security.mjs +2 -0
  280. package/dist/querying/security.mjs.map +1 -0
  281. package/dist/querying/shared/ast.d.mts +26 -0
  282. package/dist/querying/shared/ast.mjs +2 -0
  283. package/dist/querying/shared/ast.mjs.map +1 -0
  284. package/dist/querying/shared/contract.d.mts +98 -0
  285. package/dist/querying/shared/contract.mjs +2 -0
  286. package/dist/querying/shared/contract.mjs.map +1 -0
  287. package/dist/querying/shared/evaluate.d.mts +5 -0
  288. package/dist/querying/shared/evaluate.mjs +2 -0
  289. package/dist/querying/shared/evaluate.mjs.map +1 -0
  290. package/dist/querying/shared/filters.d.mts +65 -0
  291. package/dist/querying/shared/filters.mjs +2 -0
  292. package/dist/querying/shared/filters.mjs.map +1 -0
  293. package/dist/querying/shared/native-json.d.mts +7 -0
  294. package/dist/querying/shared/native-json.mjs +2 -0
  295. package/dist/querying/shared/native-json.mjs.map +1 -0
  296. package/dist/querying/shared/page.d.mts +20 -0
  297. package/dist/querying/shared/page.mjs +2 -0
  298. package/dist/querying/shared/page.mjs.map +1 -0
  299. package/dist/querying.d.mts +82 -0
  300. package/dist/querying.mjs +2 -0
  301. package/dist/querying.mjs.map +1 -0
  302. package/dist/react/failures.d.mts +24 -0
  303. package/dist/react/failures.mjs +2 -0
  304. package/dist/react/failures.mjs.map +1 -0
  305. package/dist/react/optimistic.d.mts +46 -0
  306. package/dist/react/optimistic.mjs +2 -0
  307. package/dist/react/optimistic.mjs.map +1 -0
  308. package/dist/react/pagination-state.d.mts +39 -0
  309. package/dist/react/pagination-state.mjs +2 -0
  310. package/dist/react/pagination-state.mjs.map +1 -0
  311. package/dist/react/use-command.d.mts +22 -0
  312. package/dist/react/use-command.mjs +2 -0
  313. package/dist/react/use-command.mjs.map +1 -0
  314. package/dist/react/use-paginated-list.d.mts +34 -0
  315. package/dist/react/use-paginated-list.mjs +2 -0
  316. package/dist/react/use-paginated-list.mjs.map +1 -0
  317. package/dist/react.d.mts +6 -0
  318. package/dist/react.mjs +1 -0
  319. package/dist/registration.d.mts +65 -0
  320. package/dist/registration.mjs +2 -0
  321. package/dist/registration.mjs.map +1 -0
  322. package/dist/relations-public.d.mts +2 -0
  323. package/dist/relations-public.mjs +1 -0
  324. package/dist/relations.d.mts +274 -0
  325. package/dist/relations.mjs +2 -0
  326. package/dist/relations.mjs.map +1 -0
  327. package/dist/state-machine.d.mts +1 -4
  328. package/dist/state-machine.mjs.map +1 -1
  329. package/dist/table.d.mts +222 -0
  330. package/dist/table.mjs +2 -0
  331. package/dist/table.mjs.map +1 -0
  332. package/dist/tenancy.d.mts +6 -8
  333. package/dist/tenancy.mjs +1 -1
  334. package/dist/tenancy.mjs.map +1 -1
  335. package/dist/triggers.d.mts +12 -10
  336. package/dist/triggers.mjs +1 -1
  337. package/dist/triggers.mjs.map +1 -1
  338. package/dist/webhooks.d.mts +22 -112
  339. package/dist/webhooks.mjs +1 -1
  340. package/dist/webhooks.mjs.map +1 -1
  341. package/dist/workflow.d.mts +2 -0
  342. package/dist/workflow.mjs +1 -0
  343. package/dist/zod.d.mts +30 -0
  344. package/dist/zod.mjs +2 -0
  345. package/dist/zod.mjs.map +1 -0
  346. package/package.json +145 -33
  347. package/src/test.ts +9 -17
  348. package/CHANGELOG.md +0 -145
  349. package/ROADMAP.md +0 -126
  350. package/dist/zod-table.d.mts +0 -175
  351. package/dist/zod-table.mjs +0 -2
  352. package/dist/zod-table.mjs.map +0 -1
  353. package/docs/agent-tools.md +0 -41
  354. package/docs/approvals.md +0 -200
  355. package/docs/architecture.md +0 -124
  356. package/docs/auth.md +0 -218
  357. package/docs/commands.md +0 -278
  358. package/docs/conventions.md +0 -291
  359. package/docs/crud.md +0 -62
  360. package/docs/llms.md +0 -220
  361. package/docs/maintainability.md +0 -124
  362. package/docs/migration.md +0 -351
  363. package/docs/plans/2026-08-14-001-feat-v0.1.0-feature-set-plan.md +0 -461
  364. package/docs/plans/2026-08-21-0930-feat-resolve-organization-hook-plan.md +0 -178
  365. package/docs/tenancy.md +0 -179
  366. package/docs/triggers.md +0 -75
  367. package/docs/upgrading.md +0 -175
  368. package/docs/webhooks.md +0 -58
  369. package/docs/zod-table.md +0 -173
  370. package/scripts/convex-config-bridge.mjs +0 -55
  371. package/scripts/extract-changelog.mjs +0 -29
  372. package/scripts/smoke-packed-components.mjs +0 -374
@@ -0,0 +1,2 @@
1
+ import{decodeContract as e}from"./contract.mjs";import{canonicalConvexBytes as t,captureIdempotencyInvocation as n}from"./idempotency.mjs";var r=class extends Error{_tag=`WorkflowBindingError`;constructor(e){super(e),this.name=`WorkflowBindingError`}};const i=[`version`,`operation`,`operationVersion`,`contractVersion`,`bindingVersion`,`run`,`capability`,`occurrence`,`args`],a={maxDepth:64,maxNodes:1e5,maxBytes:1e6,maxArrayLength:1e5,maxObjectFields:1e5};function o(e){if(!e||typeof e!=`object`||Object.getPrototypeOf(e)!==Object.prototype||Reflect.ownKeys(e).length!==i.length||i.some(t=>!Object.hasOwn(e,t)))throw new r(`Execution requires exact plain descriptor fields`);let n=e;for(let t of i)if(!(`value`in Object.getOwnPropertyDescriptor(e,t)))throw new r(`Execution cannot contain accessors`);if(n.version!==1||i.filter(e=>e!==`version`&&e!==`args`).some(e=>typeof n[e]!=`string`||n[e].length===0))throw new r(`Invalid execution descriptor version or identity`);try{t(n.args,a)}catch{throw new r(`Execution args require plain Convex data`)}return n}function s(e){let t=e.compatibleVersions?.map(e=>Object.freeze({...e})),n={...e};return t!==void 0&&(n.compatibleVersions=Object.freeze(t)),Object.freeze(n)}async function c(e,t,n,i={}){let a=e,s=o(n),c=[t,...t.compatibleVersions??[]];if(s.operation!==t.operation||!c.some(e=>e.operationVersion===s.operationVersion&&e.contractVersion===s.contractVersion&&e.bindingVersion===s.bindingVersion))throw new r(`Incompatible workflow operation version`);let l={...i,name:i.name??`${s.operation}:${s.occurrence}`},u;switch(t.kind){case`query`:if(!a.runQuery)throw new r(`Native query runner missing`);u=await a.runQuery(t.reference,{execution:s},l);break;case`mutation`:if(!a.runMutation)throw new r(`Native mutation runner missing`);u=await a.runMutation(t.reference,{execution:s},l);break;case`action`:if(!a.runAction)throw new r(`Native action runner missing`);if(i.inline)throw new r(`Actions cannot execute inline`);u=await a.runAction(t.reference,{execution:s},{...l,retry:i.retry??!1})}return u}async function l(t,n){let i=await e(t,n);if(i.issues)throw new r(`Workflow contract validation failed`);return i.value}function u(e){return async t=>{let n=o(t),r=await e.authorize(n);return e.execute(n,r)}}function d(e){return{handler:u({authorize:e.authorize,execute:async(t,n)=>{let r=e.receipt(n),i=await r.prepare(e.invocation(t,n));if(i.kind===`replay`)return l(r.replayResult,i.result);let a=await e.execute(t,n);return await i.complete(a),a}})}}function f(e,t){let r=o(e);return n({binding:{kind:`mutation`,atomicity:`same-mutation`},identity:{operation:r.operation,scope:t.scope,key:JSON.stringify([r.run,r.occurrence])},versions:{operation:r.operationVersion,contract:r.contractVersion,binding:r.bindingVersion,fingerprintPolicy:t.fingerprintPolicy},rawInput:r.args,canonical:{bounds:t.bounds}})}function p(e){return u({authorize:e.authorize,execute:async(n,r)=>{let i;try{i=await e.invokeMutation(n,r)}catch(n){let r=await e.terminal(n);if(r===void 0)throw n;let i=await l(e.failure,r);return t(i,a),{version:1,kind:`failed`,error:i}}return await l(e.result,i),t(i,a),{version:1,kind:`succeeded`,value:i}}})}function m(e,t){if(v(e.generation),v(t.generation),e.generation!==t.generation)return{kind:`ignored`,state:e};let n=e.nativeStatus===`running`?t.nativeStatus:e.nativeStatus,r=e.outcome??t.outcome,i=(e.status===`running`||e.status===`succeeded`)&&n===`succeeded`&&r?.kind===`failed`?`failed`:e.status===`running`?n:e.status,a={generation:e.generation,status:i,nativeStatus:n};return{kind:`applied`,state:r===void 0?a:{...a,outcome:r}}}function h(e,t){return v(t),e.generation===t?{kind:`applied`,state:{...e,status:e.status===`running`?`canceled`:e.status}}:{kind:`ignored`,state:e}}function g(e){v(e.generation),v(e.generation+1);let t={generation:e.generation+1,status:`running`,nativeStatus:`running`};return e.outcome?.kind===`succeeded`?{...t,outcome:e.outcome}:t}function _(e){async function t(t,n,r){let i={generation:t,nativeStatus:n},a=m(await e.read(),r===void 0?i:{...i,outcome:r});return a.kind===`applied`&&await e.write(t,a.state),a}return{async callback(n,r,i){return await e.authorize(),t(n,r,i)},async reconcile(n){return await e.authorize(),t(n,await e.nativeStatus(),await e.receiptOutcome())},async cancel(t){await e.authorize();let n=await e.read(),r=h(n,t);return r.kind===`applied`&&n.status===`running`&&(await e.cancelNative(),await e.write(t,r.state)),r},async restart(t){await e.authorize();let n=await e.read();if(n.generation!==t)return{kind:`ignored`,state:n};let r=g(n);return await e.restartNative(),await e.write(t,r),{kind:`applied`,state:r}}}}function v(e){if(!Number.isSafeInteger(e)||e<0)throw new r(`Invalid host execution generation`)}export{r as WorkflowBindingError,d as receiptWorkflowMutation,c as runWorkflowStep,p as terminalWorkflowAttempt,u as workflowAttempt,s as workflowBinding,h as workflowCancel,l as workflowDecode,o as workflowExecution,f as workflowReceiptInvocation,g as workflowRestart,_ as workflowStatusBindings,m as workflowTransition};
2
+ //# sourceMappingURL=workflow.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.mjs","names":["WorkflowBindingError","message","fields","descriptorBounds","workflowExecution","value","field","descriptor","canonicalConvexBytes","workflowBinding","compatibleVersions","binding","version","snapshot","runWorkflowStep","runner","step","execution","input","versions","nativeOptions","options","output","workflowDecode","decoded","decodeContract","schema","workflowAttempt","authority","configuration","receiptWorkflowMutation","adapter","preparation","workflowReceiptInvocation","captureIdempotencyInvocation","terminalWorkflowAttempt","error","terminal","safeFailure","workflowTransition","generation","current","update","nativeStatus","outcome","status","state","workflowCancel","expectedGeneration","workflowRestart","workflowStatusBindings","apply","transition"],"sources":["../../../src/modules/contracts/workflow.ts"],"sourcesContent":["import type { FunctionReference, FunctionVisibility, FunctionType } from 'convex/server'\nimport type { WorkflowCtx } from '@convex-dev/workflow'\nimport {\n\tdecodeContract,\n\ttype ContractInput,\n\ttype ContractOutput,\n\ttype NeutralSchema,\n} from './contract'\nimport {\n\tcanonicalConvexBytes,\n\tcaptureIdempotencyInvocation,\n\ttype CanonicalConvexBounds,\n\ttype IdempotencyInvocation,\n\ttype IdempotencyPreparation,\n} from './idempotency'\n\nexport class WorkflowBindingError extends Error {\n\treadonly _tag = 'WorkflowBindingError'\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'WorkflowBindingError'\n\t}\n}\nexport interface WorkflowExecution<Args = unknown> {\n\treadonly version: 1\n\treadonly operation: string\n\treadonly operationVersion: string\n\treadonly contractVersion: string\n\treadonly bindingVersion: string\n\t/** Host-issued business-run identity. Recovery preserves it. */\n\treadonly run: string\n\t/** Opaque host capability; never caller-supplied principal or tenant authority. */\n\treadonly capability: string\n\t/** Logical occurrence, distinct for each repeated loop step. */\n\treadonly occurrence: string\n\treadonly args: Args\n}\nexport type WorkflowStepArguments<Args> = { execution: WorkflowExecution<Args> }\nconst fields = [\n\t'version',\n\t'operation',\n\t'operationVersion',\n\t'contractVersion',\n\t'bindingVersion',\n\t'run',\n\t'capability',\n\t'occurrence',\n\t'args',\n] as const\nconst descriptorBounds = {\n\tmaxDepth: 64,\n\tmaxNodes: 100000,\n\tmaxBytes: 1000000,\n\tmaxArrayLength: 100000,\n\tmaxObjectFields: 100000,\n}\n/** Strict plain, versioned transport. Validity does not confer authority; the host resolves capability anew. */\n/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof -- This decoder validates an untrusted execution descriptor before it enters the native workflow boundary. */\nexport function workflowExecution<Args>(value: WorkflowExecution<Args>): WorkflowExecution<Args>\nexport function workflowExecution(value: unknown): WorkflowExecution\nexport function workflowExecution(value: unknown): WorkflowExecution {\n\tif (\n\t\t!value ||\n\t\ttypeof value !== 'object' ||\n\t\tObject.getPrototypeOf(value) !== Object.prototype ||\n\t\tReflect.ownKeys(value).length !== fields.length ||\n\t\tfields.some((field) => !Object.hasOwn(value, field))\n\t)\n\t\tthrow new WorkflowBindingError('Execution requires exact plain descriptor fields')\n\t// SAFETY: the exact field set is checked above; values and accessors are checked before use below.\n\tconst descriptor = value as WorkflowExecution\n\tfor (const field of fields)\n\t\tif (!('value' in Object.getOwnPropertyDescriptor(value, field)!))\n\t\t\tthrow new WorkflowBindingError('Execution cannot contain accessors')\n\tif (\n\t\tdescriptor.version !== 1 ||\n\t\tfields\n\t\t\t.filter((field) => field !== 'version' && field !== 'args')\n\t\t\t.some((field) => typeof descriptor[field] !== 'string' || descriptor[field].length === 0)\n\t)\n\t\tthrow new WorkflowBindingError('Invalid execution descriptor version or identity')\n\ttry {\n\t\tcanonicalConvexBytes(descriptor.args, descriptorBounds)\n\t} catch {\n\t\tthrow new WorkflowBindingError('Execution args require plain Convex data')\n\t}\n\treturn descriptor\n}\n/* oxlint-enable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof */\nexport interface WorkflowBinding<\n\tKind extends FunctionType,\n\tArgs extends NeutralSchema,\n\tResult extends NeutralSchema,\n> {\n\treadonly kind: Kind\n\treadonly operation: string\n\treadonly operationVersion: string\n\treadonly contractVersion: string\n\treadonly bindingVersion: string\n\treadonly args: Args\n\treadonly result: Result\n\treadonly reference: FunctionReference<\n\t\tNoInfer<Kind>,\n\t\tFunctionVisibility,\n\t\tWorkflowStepArguments<NoInfer<ContractInput<Args>>>,\n\t\tNoInfer<ContractInput<Result>>\n\t>\n\t/** Host explicitly lists deployed descriptor versions whose semantics remain compatible. */\n\treadonly compatibleVersions?: readonly {\n\t\toperationVersion: string\n\t\tcontractVersion: string\n\t\tbindingVersion: string\n\t}[]\n}\n/** Both phantom reference args and results must match the explicit wire contracts. */\nexport function workflowBinding<\n\tKind extends FunctionType,\n\tconst Args extends NeutralSchema,\n\tconst Result extends NeutralSchema,\n>(binding: WorkflowBinding<Kind, Args, Result>): WorkflowBinding<Kind, Args, Result> {\n\tconst compatibleVersions = binding.compatibleVersions?.map((version) =>\n\t\tObject.freeze({ ...version }),\n\t)\n\tconst snapshot = { ...binding }\n\tif (compatibleVersions !== undefined)\n\t\tsnapshot.compatibleVersions = Object.freeze(compatibleVersions)\n\treturn Object.freeze(snapshot)\n}\nexport type WorkflowStepOptions = {\n\tname?: string\n\tretry?: NonNullable<Parameters<WorkflowCtx['withOptions']>[0]['retry']>\n} & (\n\t| { inline?: false; runAt?: number; runAfter?: number }\n\t| { inline: true; runAt?: never; runAfter?: never }\n)\n/** A structural seam allows invocation-scoped native WorkflowCtx without creating another durability runtime. */\nexport interface WorkflowStepRunner {\n\t/* oxlint-disable anti-slop/no-unknown-returns -- Native runner results stay opaque here; runWorkflowStep correlates them with the binding's raw result contract without replay decoding. */\n\trunQuery?: (\n\t\treference: FunctionReference<'query', FunctionVisibility>,\n\t\targs: WorkflowStepArguments<unknown>,\n\t\toptions?: WorkflowStepOptions,\n\t) => Promise<unknown>\n\trunMutation?: (\n\t\treference: FunctionReference<'mutation', FunctionVisibility>,\n\t\targs: WorkflowStepArguments<unknown>,\n\t\toptions?: WorkflowStepOptions,\n\t) => Promise<unknown>\n\trunAction?: (\n\t\treference: FunctionReference<'action', FunctionVisibility>,\n\t\targs: WorkflowStepArguments<unknown>,\n\t\toptions?: WorkflowStepOptions,\n\t) => Promise<unknown>\n\t/* oxlint-enable anti-slop/no-unknown-returns */\n}\nexport async function runWorkflowStep<\n\tKind extends FunctionType,\n\tArgs extends NeutralSchema,\n\tResult extends NeutralSchema,\n>(\n\tstep: WorkflowCtx | WorkflowStepRunner,\n\tbinding: WorkflowBinding<Kind, Args, Result>,\n\tinput: WorkflowExecution<ContractInput<Args>>,\n\toptions: WorkflowStepOptions = {},\n): Promise<ContractInput<Result>> {\n\t// SAFETY: each binding has nonempty, checked generated args. Native ArgsAndOptions' empty-args overload is never selected.\n\tconst runner = step as WorkflowStepRunner\n\tconst execution = workflowExecution(input)\n\tconst versions = [binding, ...(binding.compatibleVersions ?? [])]\n\tif (\n\t\texecution.operation !== binding.operation ||\n\t\t!versions.some(\n\t\t\t(version) =>\n\t\t\t\tversion.operationVersion === execution.operationVersion &&\n\t\t\t\tversion.contractVersion === execution.contractVersion &&\n\t\t\t\tversion.bindingVersion === execution.bindingVersion,\n\t\t)\n\t)\n\t\tthrow new WorkflowBindingError('Incompatible workflow operation version')\n\tconst nativeOptions = {\n\t\t...options,\n\t\tname: options.name ?? `${execution.operation}:${execution.occurrence}`,\n\t}\n\tlet output: unknown\n\tswitch (binding.kind) {\n\t\tcase 'query':\n\t\t\tif (!runner.runQuery) throw new WorkflowBindingError('Native query runner missing')\n\t\t\t// SAFETY: the checked binding kind selects this exact native reference kind.\n\t\t\toutput = await runner.runQuery(\n\t\t\t\tbinding.reference as FunctionReference<'query', FunctionVisibility>,\n\t\t\t\t{ execution },\n\t\t\t\tnativeOptions,\n\t\t\t)\n\t\t\tbreak\n\t\tcase 'mutation':\n\t\t\tif (!runner.runMutation) throw new WorkflowBindingError('Native mutation runner missing')\n\t\t\t// SAFETY: the checked binding kind selects this exact native reference kind.\n\t\t\toutput = await runner.runMutation(\n\t\t\t\tbinding.reference as FunctionReference<'mutation', FunctionVisibility>,\n\t\t\t\t{ execution },\n\t\t\t\tnativeOptions,\n\t\t\t)\n\t\t\tbreak\n\t\tcase 'action':\n\t\t\tif (!runner.runAction) throw new WorkflowBindingError('Native action runner missing')\n\t\t\tif (options.inline) throw new WorkflowBindingError('Actions cannot execute inline')\n\t\t\t// SAFETY: the checked binding kind selects this exact native reference kind.\n\t\t\toutput = await runner.runAction(\n\t\t\t\tbinding.reference as FunctionReference<'action', FunctionVisibility>,\n\t\t\t\t{ execution },\n\t\t\t\t{ ...nativeOptions, retry: options.retry ?? false },\n\t\t\t)\n\t\t\tbreak\n\t}\n\t// Native validators own wire validation. Replaying workflow code must not rerun transforms.\n\t// SAFETY: the binding correlates the generated reference's result with this raw wire contract.\n\treturn output as ContractInput<Result>\n}\nexport async function workflowDecode<S extends NeutralSchema>(\n\tschema: S,\n\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- The schema parses retained or native transport values at this boundary.\n\tvalue: unknown,\n): Promise<ContractOutput<S>> {\n\tconst decoded = await decodeContract(schema, value)\n\tif (decoded.issues) throw new WorkflowBindingError('Workflow contract validation failed')\n\treturn decoded.value\n}\ntype Ordinary<A> = A | PromiseLike<A>\n/** This helper belongs inside a registered native function, never in the replaying workflow handler. */\nexport function workflowAttempt<Args, Authority, Result>(configuration: {\n\tauthorize: (execution: WorkflowExecution<Args>) => Ordinary<Authority>\n\texecute: (execution: WorkflowExecution<Args>, authority: Authority) => Ordinary<Result>\n}) {\n\treturn async (input: WorkflowExecution<Args>): Promise<Result> => {\n\t\tconst execution = workflowExecution(input)\n\t\tconst authority = await configuration.authorize(execution)\n\t\treturn configuration.execute(execution, authority)\n\t}\n}\nexport type WorkflowOutcome<Result = unknown, Failure = unknown> =\n\t| { readonly version: 1; readonly kind: 'succeeded'; readonly value: Result }\n\t| { readonly version: 1; readonly kind: 'failed'; readonly error: Failure }\ndeclare const protectedMutation: unique symbol\nexport interface ReceiptProtectedWorkflowMutation<Args, Result> {\n\treadonly [protectedMutation]: { args: Args; result: Result }\n\treadonly handler: (execution: WorkflowExecution<Args>) => Promise<Result>\n}\nexport interface WorkflowReceiptAdapter<S extends NeutralSchema> {\n\treadonly replayResult: S\n\treadonly prepare: (\n\t\tinvocation: IdempotencyInvocation,\n\t) => Promise<IdempotencyPreparation<ContractOutput<S>>>\n}\n/** Host registers this handler as the inner native mutation. All callbacks share its transaction. */\nexport function receiptWorkflowMutation<\n\tArgs,\n\tAuthority,\n\tconst Replay extends NeutralSchema,\n>(configuration: {\n\tauthorize: (execution: WorkflowExecution<Args>) => Ordinary<Authority>\n\treceipt: (authority: Authority) => WorkflowReceiptAdapter<Replay>\n\tinvocation: (execution: WorkflowExecution<Args>, authority: Authority) => IdempotencyInvocation\n\texecute: (\n\t\texecution: WorkflowExecution<Args>,\n\t\tauthority: Authority,\n\t) => Ordinary<ContractOutput<Replay>>\n}): ReceiptProtectedWorkflowMutation<Args, ContractOutput<Replay>> {\n\tconst handler = workflowAttempt({\n\t\tauthorize: configuration.authorize,\n\t\texecute: async (execution: WorkflowExecution<Args>, authority: Authority) => {\n\t\t\tconst adapter = configuration.receipt(authority)\n\t\t\tconst preparation = await adapter.prepare(configuration.invocation(execution, authority))\n\t\t\tif (preparation.kind === 'replay')\n\t\t\t\treturn workflowDecode(adapter.replayResult, preparation.result)\n\t\t\tconst value = await configuration.execute(execution, authority)\n\t\t\tawait preparation.complete(value)\n\t\t\treturn value\n\t\t},\n\t})\n\t// SAFETY: the private type evidence can only be issued by this receipt-protected helper.\n\treturn { handler } as ReceiptProtectedWorkflowMutation<Args, ContractOutput<Replay>>\n}\nexport function workflowReceiptInvocation(\n\texecution: WorkflowExecution,\n\toptions: { scope: string; fingerprintPolicy: string; bounds: CanonicalConvexBounds },\n): IdempotencyInvocation {\n\tconst descriptor = workflowExecution(execution)\n\treturn captureIdempotencyInvocation({\n\t\tbinding: { kind: 'mutation', atomicity: 'same-mutation' },\n\t\tidentity: {\n\t\t\toperation: descriptor.operation,\n\t\t\tscope: options.scope,\n\t\t\tkey: JSON.stringify([descriptor.run, descriptor.occurrence]),\n\t\t},\n\t\tversions: {\n\t\t\toperation: descriptor.operationVersion,\n\t\t\tcontract: descriptor.contractVersion,\n\t\t\tbinding: descriptor.bindingVersion,\n\t\t\tfingerprintPolicy: options.fingerprintPolicy,\n\t\t},\n\t\trawInput: descriptor.args,\n\t\tcanonical: { bounds: options.bounds },\n\t})\n}\ntype TerminalMode<Args> =\n\t| {\n\t\t\tkind: 'mutation'\n\t\t\t/** Assertion supplied only after host native rollback/journaling acceptance. */ atomicJournalProof: 'host-verified'\n\t }\n\t| { kind: 'action'; protectedMutation: ReceiptProtectedWorkflowMutation<Args, unknown> }\n/** The native inner mutation rejection must cross its transaction boundary before terminal mapping. */\nexport function terminalWorkflowAttempt<\n\tArgs,\n\tAuthority,\n\tconst Result extends NeutralSchema,\n\tconst Failure extends NeutralSchema,\n>(\n\tconfiguration: TerminalMode<Args> & {\n\t\tauthorize: (execution: WorkflowExecution<Args>) => Ordinary<Authority>\n\t\tinvokeMutation: (\n\t\t\texecution: WorkflowExecution<Args>,\n\t\t\tauthority: Authority,\n\t\t) => Promise<ContractInput<Result>>\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Native thrown values are classified by the host before validating the terminal failure contract.\n\t\tterminal: (error: unknown) => Ordinary<ContractInput<Failure> | undefined>\n\t\tresult: Result\n\t\tfailure: Failure\n\t},\n) {\n\treturn workflowAttempt({\n\t\tauthorize: configuration.authorize,\n\t\texecute: async (\n\t\t\texecution: WorkflowExecution<Args>,\n\t\t\tauthority: Authority,\n\t\t): Promise<WorkflowOutcome<ContractInput<Result>, ContractOutput<Failure>>> => {\n\t\t\tlet value: ContractInput<Result>\n\t\t\ttry {\n\t\t\t\tvalue = await configuration.invokeMutation(execution, authority)\n\t\t\t} catch (error) {\n\t\t\t\tconst terminal = await configuration.terminal(error)\n\t\t\t\tif (terminal === undefined) throw error\n\t\t\t\tconst safeFailure = await workflowDecode(configuration.failure, terminal)\n\t\t\t\tcanonicalConvexBytes(safeFailure, descriptorBounds)\n\t\t\t\treturn { version: 1, kind: 'failed', error: safeFailure }\n\t\t\t}\n\t\t\tawait workflowDecode(configuration.result, value)\n\t\t\tcanonicalConvexBytes(value, descriptorBounds)\n\t\t\treturn { version: 1, kind: 'succeeded', value }\n\t\t},\n\t})\n}\nexport type WorkflowNativeStatus = 'running' | 'succeeded' | 'failed' | 'canceled'\nexport interface WorkflowHostState<Result = unknown, Failure = unknown> {\n\treadonly generation: number\n\treadonly status: WorkflowNativeStatus\n\treadonly nativeStatus: WorkflowNativeStatus\n\treadonly outcome?: WorkflowOutcome<Result, Failure>\n}\nexport interface WorkflowHostUpdate<Result = unknown, Failure = unknown> {\n\treadonly generation: number\n\treadonly nativeStatus: WorkflowNativeStatus\n\treadonly outcome?: WorkflowOutcome<Result, Failure>\n}\nexport type WorkflowTransition<Result = unknown, Failure = unknown> = {\n\treadonly kind: 'applied' | 'ignored'\n\treadonly state: WorkflowHostState<Result, Failure>\n}\n/** Call within a host transaction or compare-and-set. A late operation failure refines host success; cancellation and terminal native status stay fenced. */\nexport function workflowTransition<Result, Failure>(\n\tcurrent: WorkflowHostState<Result, Failure>,\n\tupdate: WorkflowHostUpdate<Result, Failure>,\n): WorkflowTransition<Result, Failure> {\n\tgeneration(current.generation)\n\tgeneration(update.generation)\n\tif (current.generation !== update.generation) return { kind: 'ignored', state: current }\n\tconst nativeStatus =\n\t\tcurrent.nativeStatus !== 'running' ? current.nativeStatus : update.nativeStatus\n\tconst outcome = current.outcome ?? update.outcome\n\tconst status =\n\t\t(current.status === 'running' || current.status === 'succeeded') &&\n\t\tnativeStatus === 'succeeded' &&\n\t\toutcome?.kind === 'failed'\n\t\t\t? 'failed'\n\t\t\t: current.status !== 'running'\n\t\t\t\t? current.status\n\t\t\t\t: nativeStatus\n\tconst state = { generation: current.generation, status, nativeStatus }\n\treturn { kind: 'applied', state: outcome === undefined ? state : { ...state, outcome } }\n}\nexport function workflowCancel<Result, Failure>(\n\tcurrent: WorkflowHostState<Result, Failure>,\n\texpectedGeneration: number,\n): WorkflowTransition<Result, Failure> {\n\tgeneration(expectedGeneration)\n\tif (current.generation !== expectedGeneration) return { kind: 'ignored', state: current }\n\treturn {\n\t\tkind: 'applied',\n\t\tstate: { ...current, status: current.status === 'running' ? 'canceled' : current.status },\n\t}\n}\n/** Host calls after an authorized native restart. Receipt identity remains run plus occurrence. */\nexport function workflowRestart<Result, Failure>(\n\tcurrent: WorkflowHostState<Result, Failure>,\n): WorkflowHostState<Result, Failure> {\n\tgeneration(current.generation)\n\tgeneration(current.generation + 1)\n\tconst state = {\n\t\tgeneration: current.generation + 1,\n\t\tstatus: 'running' as const,\n\t\tnativeStatus: 'running' as const,\n\t}\n\treturn current.outcome?.kind === 'succeeded' ? { ...state, outcome: current.outcome } : state\n}\n/** Host closures capture the trusted run, secured storage and manager. `write` must enforce expected generation atomically. */\nexport function workflowStatusBindings<Result, Failure>(configuration: {\n\tauthorize: () => Ordinary<void>\n\tread: () => Ordinary<WorkflowHostState<Result, Failure>>\n\twrite: (expectedGeneration: number, state: WorkflowHostState<Result, Failure>) => Ordinary<void>\n\tnativeStatus: () => Ordinary<WorkflowNativeStatus>\n\treceiptOutcome: () => Ordinary<WorkflowOutcome<Result, Failure> | undefined>\n\t/** Host calls the manager in the same transaction as its guarded state write. */\n\tcancelNative: () => Ordinary<void>\n\trestartNative: () => Ordinary<void>\n}) {\n\tasync function apply(\n\t\texpectedGeneration: number,\n\t\tnativeStatus: WorkflowNativeStatus,\n\t\toutcome?: WorkflowOutcome<Result, Failure>,\n\t) {\n\t\tconst update = { generation: expectedGeneration, nativeStatus }\n\t\tconst transition = workflowTransition(\n\t\t\tawait configuration.read(),\n\t\t\toutcome === undefined ? update : { ...update, outcome },\n\t\t)\n\t\tif (transition.kind === 'applied')\n\t\t\tawait configuration.write(expectedGeneration, transition.state)\n\t\treturn transition\n\t}\n\treturn {\n\t\tasync callback(\n\t\t\texpectedGeneration: number,\n\t\t\tnativeStatus: WorkflowNativeStatus,\n\t\t\toutcome?: WorkflowOutcome<Result, Failure>,\n\t\t) {\n\t\t\tawait configuration.authorize()\n\t\t\treturn apply(expectedGeneration, nativeStatus, outcome)\n\t\t},\n\t\tasync reconcile(expectedGeneration: number) {\n\t\t\tawait configuration.authorize()\n\t\t\treturn apply(\n\t\t\t\texpectedGeneration,\n\t\t\t\tawait configuration.nativeStatus(),\n\t\t\t\tawait configuration.receiptOutcome(),\n\t\t\t)\n\t\t},\n\t\tasync cancel(expectedGeneration: number) {\n\t\t\tawait configuration.authorize()\n\t\t\tconst current = await configuration.read()\n\t\t\tconst transition = workflowCancel(current, expectedGeneration)\n\t\t\tif (transition.kind === 'applied' && current.status === 'running') {\n\t\t\t\tawait configuration.cancelNative()\n\t\t\t\tawait configuration.write(expectedGeneration, transition.state)\n\t\t\t}\n\t\t\treturn transition\n\t\t},\n\t\tasync restart(expectedGeneration: number) {\n\t\t\tawait configuration.authorize()\n\t\t\tconst current = await configuration.read()\n\t\t\tif (current.generation !== expectedGeneration)\n\t\t\t\treturn { kind: 'ignored' as const, state: current }\n\t\t\tconst state = workflowRestart(current)\n\t\t\tawait configuration.restartNative()\n\t\t\tawait configuration.write(expectedGeneration, state)\n\t\t\treturn { kind: 'applied' as const, state }\n\t\t},\n\t}\n}\nfunction generation(value: number): void {\n\tif (!Number.isSafeInteger(value) || value < 0)\n\t\tthrow new WorkflowBindingError('Invalid host execution generation')\n}\n"],"mappings":"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"}
@@ -0,0 +1,63 @@
1
+ import { AuditEntryInput } from "../../components/foundation/client.mjs";
2
+ import { Observability } from "../../components/foundation/modules/observability/observability.mjs";
3
+ import { DomainActionContract, DomainAuditInput, DomainContract } from "../contracts/domain.mjs";
4
+ import { BoundOperations } from "../contracts/binding.mjs";
5
+ import { DomainOf, HostOf, HostParameter, Registry, Resolver, createEffectCommand } from "./command.mjs";
6
+ import { AuditValue, AuditedOperations, DomainEffectFactory, DomainEffectImplementations, ExactDomainOperations } from "./domain.mjs";
7
+ import { FailureAuditOptions } from "./failure-audit.mjs";
8
+ import { CallbackError, CallbackRequirements, ValidatedEffectOperations, effectActionFactory } from "./operation.mjs";
9
+ import { NestedAuditMode, RequestScope } from "./scope.mjs";
10
+ import { Effect } from "effect";
11
+ type Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>;
12
+ /** Host policies an Action registry uses; actions have no mutation-side permission host. */
13
+ export type EffectActionDependencies = {
14
+ observability: Observability;
15
+ /** Writes action audit entries, typically through `ctx.runMutation`; required once any action audits. */
16
+ writeActionAudit?: (host: never, entry: AuditEntryInput) => Supported<unknown>;
17
+ auditFailure?: FailureAuditOptions;
18
+ nestedAudit?: NestedAuditMode;
19
+ };
20
+ type ActionWriter<Dependencies extends EffectActionDependencies> = [Exclude<Dependencies['writeActionAudit'], undefined>] extends [never] ? (host: never, entry: AuditEntryInput) => void : Exclude<Dependencies['writeActionAudit'], undefined>;
21
+ /** The command kernel runs actions with the action writer in its audit-writer slot. */
22
+ type KernelDependencies<Dependencies extends EffectActionDependencies> = {
23
+ observability: Observability;
24
+ writeAudit: ActionWriter<Dependencies>;
25
+ auditFailure?: FailureAuditOptions;
26
+ nestedAudit?: NestedAuditMode;
27
+ };
28
+ type ActionCompatible<Resolve extends Resolver, Dependencies extends EffectActionDependencies> = [HostOf<Resolve>] extends [HostParameter<Dependencies['writeActionAudit']>] ? unknown : {
29
+ context: never;
30
+ };
31
+ type ActionFactory<Resolve extends Resolver, Guard> = ReturnType<typeof effectActionFactory<DomainOf<Resolve>, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>>>;
32
+ type Kernel<Resolve extends Resolver, Operations extends Registry<DomainOf<Resolve>>, Dependencies extends EffectActionDependencies, Guard> = ReturnType<typeof createEffectCommand<Resolve, Operations, KernelDependencies<Dependencies>, Guard>>;
33
+ /** Actions are executed by their own Convex action functions; they are never exposed as mutations. */
34
+ export type EffectActionRegistry<Resolve extends Resolver, Operations extends Registry<DomainOf<Resolve>>, Dependencies extends EffectActionDependencies, Guard> = Pick<Kernel<Resolve, Operations, Dependencies, Guard>, 'exec' | 'withContext'>;
35
+ export declare class ActionAuditWriterError extends Error {
36
+ readonly code = "ACTION_AUDIT_WRITER_MISSING";
37
+ readonly name = "ActionAuditWriterError";
38
+ constructor(operation: string);
39
+ }
40
+ /** Bind trusted application policies once; each registry resolves its own invocation context. */
41
+ export declare function bindEffectAction<const Dependencies extends EffectActionDependencies>(dependencies: Dependencies): {
42
+ <Resolve extends Resolver, const Contract extends DomainContract & {
43
+ actions: Readonly<Record<string, DomainActionContract>>;
44
+ }, const Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['actions']>, Returned extends AuditValue = never, Guard = never>(configuration: {
45
+ contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['actions']> & ValidatedEffectOperations<Operations> ? unknown : never>;
46
+ context: Resolve;
47
+ audit?: (resolution: DomainAuditInput<Contract['actions']>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
48
+ operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['actions'], 'action', never, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>, Contract['errors']>) => Operations;
49
+ defaults?: {
50
+ guard?: (context: DomainOf<Resolve>) => Guard;
51
+ };
52
+ } & ActionCompatible<Resolve, Dependencies>): EffectActionRegistry<Resolve, [Returned] extends [never] ? BoundOperations<Operations, Contract['actions']> : AuditedOperations<BoundOperations<Operations, Contract['actions']>, (resolution: never, context: never) => Returned>, Dependencies, Guard>;
53
+ <Resolve extends Resolver, const Operations extends Registry<DomainOf<Resolve>>, Returned extends AuditValue = never, Guard = never>(configuration: {
54
+ context: Resolve;
55
+ audit?: (resolution: DomainAuditInput<Operations>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
56
+ operations: (define: ActionFactory<Resolve, Guard>) => Operations & NoInfer<ValidatedEffectOperations<Operations>>;
57
+ defaults?: {
58
+ guard?: (context: DomainOf<Resolve>) => Guard;
59
+ };
60
+ } & ActionCompatible<Resolve, Dependencies>): EffectActionRegistry<Resolve, [Returned] extends [never] ? Operations : AuditedOperations<Operations, (resolution: never, context: never) => Returned>, Dependencies, Guard>;
61
+ };
62
+ export {};
63
+ //# sourceMappingURL=action.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{snapshotOperations as e}from"../contracts/binding.mjs";import{memoize as t,registerLazyRegistry as n}from"../contracts/lazy.mjs";import{createEffectCommand as r}from"./command.mjs";import{domainEffectFactory as i}from"./domain.mjs";import{effectActionFactory as a}from"./operation.mjs";var o=class extends Error{code=`ACTION_AUDIT_WRITER_MISSING`;name=`ActionAuditWriterError`;constructor(e){super(`Action "${e}" declares an audit but the Foundation has no writeActionAudit`)}};function s(s){function c(c){let l=t(()=>{let t=e(c.operations(c.contract?i(c.contract.actions??{},`action`,c.contract.errors):a()),c.contract,`actions`,c.audit);if(!s.writeActionAudit){for(let[e,n]of Object.entries(t))if(`audit`in n&&n.audit!==void 0)throw new o(e)}return t}),u=r({...c,observability:s.observability,auditFailure:s.auditFailure,nestedAudit:s.nestedAudit,writeAudit:s.writeActionAudit??(()=>void 0),operations:l,mode:`action`});return n({exec:u.exec,withContext:u.withContext},l)}return c}export{o as ActionAuditWriterError,s as bindEffectAction};
2
+ //# sourceMappingURL=action.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"action.mjs","names":["ActionAuditWriterError","operation","bindEffectAction","action","getOperations","memoize","operations","snapshotOperations","configuration","domainEffectFactory","effectActionFactory","dependencies","definition","kernel","createEffectCommand","registerLazyRegistry"],"sources":["../../../src/modules/effect/action.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type -- Overload implementation storage is erased; public signatures retain concrete values, errors and services. */\nimport type { Effect } from 'effect'\nimport type { AuditEntryInput } from '../../components/foundation/client'\n// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation observability without entering the Convex component deployment graph.\nimport type { Observability } from '../../components/foundation/modules/observability/observability'\nimport type { DomainActionContract, DomainAuditInput, DomainContract } from '../contracts/domain'\nimport { snapshotOperations, type BoundOperations } from '../contracts/binding'\nimport { memoize, registerLazyRegistry } from '../contracts/lazy'\nimport {\n\tcreateEffectCommand,\n\ttype DomainOf,\n\ttype HostOf,\n\ttype HostParameter,\n\ttype Registry,\n\ttype Resolver,\n} from './command'\nimport {\n\tdomainEffectFactory,\n\ttype AuditedOperations,\n\ttype AuditValue,\n\ttype DomainEffectFactory,\n\ttype DomainEffectImplementations,\n\ttype ExactDomainOperations,\n} from './domain'\nimport type { FailureAuditOptions } from './failure-audit'\nimport {\n\teffectActionFactory,\n\ttype CallbackError,\n\ttype CallbackRequirements,\n\ttype ValidatedEffectOperations,\n} from './operation'\nimport type { NestedAuditMode, RequestScope } from './scope'\n\ntype Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>\n\n/** Host policies an Action registry uses; actions have no mutation-side permission host. */\nexport type EffectActionDependencies = {\n\tobservability: Observability\n\t/** Writes action audit entries, typically through `ctx.runMutation`; required once any action audits. */\n\twriteActionAudit?: (host: never, entry: AuditEntryInput) => Supported<unknown>\n\tauditFailure?: FailureAuditOptions\n\tnestedAudit?: NestedAuditMode\n}\ntype ActionWriter<Dependencies extends EffectActionDependencies> = [\n\tExclude<Dependencies['writeActionAudit'], undefined>,\n] extends [never]\n\t? (host: never, entry: AuditEntryInput) => void\n\t: Exclude<Dependencies['writeActionAudit'], undefined>\n/** The command kernel runs actions with the action writer in its audit-writer slot. */\ntype KernelDependencies<Dependencies extends EffectActionDependencies> = {\n\tobservability: Observability\n\twriteAudit: ActionWriter<Dependencies>\n\tauditFailure?: FailureAuditOptions\n\tnestedAudit?: NestedAuditMode\n}\ntype ActionCompatible<Resolve extends Resolver, Dependencies extends EffectActionDependencies> = [\n\tHostOf<Resolve>,\n] extends [HostParameter<Dependencies['writeActionAudit']>]\n\t? unknown\n\t: { context: never }\ntype ActionFactory<Resolve extends Resolver, Guard> = ReturnType<\n\ttypeof effectActionFactory<\n\t\tDomainOf<Resolve>,\n\t\tNoInfer<CallbackError<Guard>>,\n\t\tNoInfer<CallbackRequirements<Guard>>\n\t>\n>\ntype Kernel<\n\tResolve extends Resolver,\n\tOperations extends Registry<DomainOf<Resolve>>,\n\tDependencies extends EffectActionDependencies,\n\tGuard,\n> = ReturnType<\n\ttypeof createEffectCommand<Resolve, Operations, KernelDependencies<Dependencies>, Guard>\n>\n/** Actions are executed by their own Convex action functions; they are never exposed as mutations. */\nexport type EffectActionRegistry<\n\tResolve extends Resolver,\n\tOperations extends Registry<DomainOf<Resolve>>,\n\tDependencies extends EffectActionDependencies,\n\tGuard,\n> = Pick<Kernel<Resolve, Operations, Dependencies, Guard>, 'exec' | 'withContext'>\n\nexport class ActionAuditWriterError extends Error {\n\treadonly code = 'ACTION_AUDIT_WRITER_MISSING'\n\treadonly name = 'ActionAuditWriterError'\n\tconstructor(operation: string) {\n\t\tsuper(`Action \"${operation}\" declares an audit but the Foundation has no writeActionAudit`)\n\t}\n}\n\n/** Bind trusted application policies once; each registry resolves its own invocation context. */\nexport function bindEffectAction<const Dependencies extends EffectActionDependencies>(\n\tdependencies: Dependencies,\n) {\n\tfunction action<\n\t\tResolve extends Resolver,\n\t\tconst Contract extends DomainContract & {\n\t\t\tactions: Readonly<Record<string, DomainActionContract>>\n\t\t},\n\t\tconst Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['actions']>,\n\t\tReturned extends AuditValue = never,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontract: Contract &\n\t\t\t\tNoInfer<\n\t\t\t\t\tOperations extends ExactDomainOperations<Operations, Contract['actions']> &\n\t\t\t\t\t\tValidatedEffectOperations<Operations>\n\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t: never\n\t\t\t\t>\n\t\t\tcontext: Resolve\n\t\t\taudit?: (\n\t\t\t\tresolution: DomainAuditInput<Contract['actions']>,\n\t\t\t\tcontext: DomainOf<Resolve>,\n\t\t\t\tscope: RequestScope | undefined,\n\t\t\t) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: DomainEffectFactory<\n\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\tContract['actions'],\n\t\t\t\t\t'action',\n\t\t\t\t\tnever,\n\t\t\t\t\tNoInfer<CallbackError<Guard>>,\n\t\t\t\t\tNoInfer<CallbackRequirements<Guard>>,\n\t\t\t\t\tContract['errors']\n\t\t\t\t>,\n\t\t\t) => Operations\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & ActionCompatible<Resolve, Dependencies>,\n\t): EffectActionRegistry<\n\t\tResolve,\n\t\t[Returned] extends [never]\n\t\t\t? BoundOperations<Operations, Contract['actions']>\n\t\t\t: AuditedOperations<\n\t\t\t\t\tBoundOperations<Operations, Contract['actions']>,\n\t\t\t\t\t(resolution: never, context: never) => Returned\n\t\t\t\t>,\n\t\tDependencies,\n\t\tGuard\n\t>\n\tfunction action<\n\t\tResolve extends Resolver,\n\t\tconst Operations extends Registry<DomainOf<Resolve>>,\n\t\tReturned extends AuditValue = never,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontext: Resolve\n\t\t\taudit?: (\n\t\t\t\tresolution: DomainAuditInput<Operations>,\n\t\t\t\tcontext: DomainOf<Resolve>,\n\t\t\t\tscope: RequestScope | undefined,\n\t\t\t) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: ActionFactory<Resolve, Guard>,\n\t\t\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & ActionCompatible<Resolve, Dependencies>,\n\t): EffectActionRegistry<\n\t\tResolve,\n\t\t[Returned] extends [never]\n\t\t\t? Operations\n\t\t\t: AuditedOperations<Operations, (resolution: never, context: never) => Returned>,\n\t\tDependencies,\n\t\tGuard\n\t>\n\tfunction action(configuration: {\n\t\tcontext: Resolver\n\t\tcontract?: DomainContract\n\t\taudit?: (resolution: never, context: never, scope: never) => AuditValue\n\t\toperations: (define: never) => Readonly<Record<string, object>>\n\t\tdefaults?: { guard?: (context: never) => unknown }\n\t}): unknown {\n\t\tconst buildOperations = () => {\n\t\t\tconst operations = snapshotOperations(\n\t\t\t\tconfiguration.operations(\n\t\t\t\t\t// SAFETY: each overload checks callbacks against this exact inline or contracted helper factory.\n\t\t\t\t\t(configuration.contract\n\t\t\t\t\t\t? domainEffectFactory(\n\t\t\t\t\t\t\t\tconfiguration.contract.actions ?? {},\n\t\t\t\t\t\t\t\t'action',\n\t\t\t\t\t\t\t\tconfiguration.contract.errors,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: effectActionFactory()) as never,\n\t\t\t\t),\n\t\t\t\tconfiguration.contract,\n\t\t\t\t'actions',\n\t\t\t\tconfiguration.audit,\n\t\t\t)\n\t\t\tif (!dependencies.writeActionAudit) {\n\t\t\t\tfor (const [operation, definition] of Object.entries(operations))\n\t\t\t\t\tif ('audit' in definition && definition.audit !== undefined)\n\t\t\t\t\t\tthrow new ActionAuditWriterError(operation)\n\t\t\t}\n\t\t\treturn operations\n\t\t}\n\t\tconst getOperations = memoize(buildOperations)\n\t\t// SAFETY: overloads check callbacks and schemas; binding validates exact keys and snapshots runtime records.\n\t\tconst kernel = createEffectCommand({\n\t\t\t...configuration,\n\t\t\tobservability: dependencies.observability,\n\t\t\tauditFailure: dependencies.auditFailure,\n\t\t\tnestedAudit: dependencies.nestedAudit,\n\t\t\twriteAudit: dependencies.writeActionAudit ?? (() => undefined),\n\t\t\toperations: getOperations,\n\t\t\tmode: 'action',\n\t\t} as never)\n\t\treturn registerLazyRegistry(\n\t\t\t{ exec: kernel.exec, withContext: kernel.withContext },\n\t\t\tgetOperations,\n\t\t)\n\t}\n\treturn action\n}\n"],"mappings":"A,qSAmFA,IAAaA,EAAb,cAA4C,KAAM,CACjD,KAAgB,8BAChB,KAAgB,yBAChB,YAAY,EAAmB,CAC9B,MAAM,WAAWC,EAAU,+DAA+D,CAC3F,CACD,EAGA,SAAgBC,EACf,EACC,CA0ED,SAASC,EAAO,EAMJ,CAwBX,IAAMC,EAAgBC,MAvBQ,CAC7B,IAAMC,EAAaC,EAClBC,EAAc,WAEZA,EAAc,SACZC,EACAD,EAAc,SAAS,SAAW,CAAC,EACnC,SACAA,EAAc,SAAS,MACxB,EACCE,EAAoB,CACxB,EACAF,EAAc,SACd,UACAA,EAAc,KACf,EACA,GAAI,CAACG,EAAa,iBACZ,KAAA,GAAM,CAACV,EAAWW,KAAe,OAAO,QAAQN,CAAU,EAC9D,GAAI,UAAWM,GAAcA,EAAW,QAAU,IAAA,GACjD,MAAM,IAAIZ,EAAuBC,CAAS,CAAA,CAE7C,OAAOK,CACR,CAC6C,EAEvCO,EAASC,EAAoB,CAClC,GAAGN,EACH,cAAeG,EAAa,cAC5B,aAAcA,EAAa,aAC3B,YAAaA,EAAa,YAC1B,WAAYA,EAAa,uBAA2B,IAAA,IACpD,WAAYP,EACZ,KAAM,QACP,CAAU,EACV,OAAOW,EACN,CAAE,KAAMF,EAAO,KAAM,YAAaA,EAAO,WAAY,EACrDT,CACD,CACD,CACA,OAAOD,CACR,C"}
@@ -0,0 +1,2 @@
1
+ import { OperationExecutor, OperationPublicResult, OperationTool, OperationToolConverter, OperationToolDefinition, OperationToolJsonSchema, OperationToolOutcome, SelectedOperation, bindOperationExecutor, createOperationTools, operationToolDialect, selectOperation } from "../contracts/exposure.mjs";
2
+ export { type OperationExecutor, type OperationPublicResult, type OperationTool, type OperationToolConverter, type OperationToolDefinition, type OperationToolJsonSchema, type OperationToolOutcome, type SelectedOperation, bindOperationExecutor, createOperationTools, operationToolDialect, selectOperation };
@@ -0,0 +1 @@
1
+ export{bindOperationExecutor,createOperationTools,operationToolDialect,selectOperation}from"../contracts/exposure.mjs";
@@ -0,0 +1,36 @@
1
+ import { ErrorContract, ErrorDefinitions } from "../contracts/errors.mjs";
2
+ import { CallbackRequirements, EffectValue } from "./operation.mjs";
3
+ import { Context, Effect, Scope } from "effect";
4
+ export type EffectApiErrorProjection = (error: unknown) => unknown;
5
+ export type EffectApiErrorContract = Pick<ErrorContract<ErrorDefinitions>, 'project'>;
6
+ export type EffectApiHandlerValue<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>;
7
+ export type EffectApiServices = Context.Context<never> | PromiseLike<Context.Context<never>> | Effect.Effect<Context.Context<never>, unknown, Scope.Scope>;
8
+ export type ProvidedServices<Provider> = EffectValue<Provider> extends Context.Context<infer Services> ? Services : never;
9
+ export type EffectApiContext = EffectApiHandlerValue<Record<string, unknown>>;
10
+ type KeysOfUnion<Value> = Value extends object ? keyof Value : never;
11
+ export type CheckedContext<Ctx, Added> = Extract<KeysOfUnion<EffectValue<Added>>, keyof Ctx> extends never ? unknown : never;
12
+ export type EffectApiOptions<Ctx, Provider extends EffectApiServices, Added = {}> = ([ProvidedServices<Provider>] extends [never] ? {
13
+ services?: (ctx: Ctx) => Provider;
14
+ } : {
15
+ services: (ctx: Ctx) => Provider;
16
+ }) & ([KeysOfUnion<EffectValue<Added>>] extends [never] ? {
17
+ context?: (ctx: Ctx) => Added & CheckedContext<Ctx, Added>;
18
+ } : {
19
+ context: (ctx: Ctx) => Added & CheckedContext<Ctx, Added>;
20
+ }) & ({
21
+ errors: EffectApiErrorContract;
22
+ mapError?: never;
23
+ } | {
24
+ errors?: never;
25
+ mapError?: EffectApiErrorProjection;
26
+ });
27
+ export type CheckedApiRequirements<Returned, Provider> = [Exclude<CallbackRequirements<NoInfer<Returned>>, ProvidedServices<Provider> | Scope.Scope>] extends [never] ? unknown : never;
28
+ /** Internal erasure is limited to the registration boundary; public adapters check A/E/R. */
29
+ export declare function wrapEffectBuilder(builder: Function, options: {
30
+ services?: Function;
31
+ context?: Function;
32
+ mapError?: EffectApiErrorProjection;
33
+ errors?: EffectApiErrorContract;
34
+ }): Function;
35
+ export {};
36
+ //# sourceMappingURL=api-runtime.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{memoize as e}from"../contracts/lazy.mjs";import{getArgumentRejection as t,projectErrorCause as n}from"./errors.mjs";import{normalizeEffect as r}from"./normalize.mjs";import{ConvexError as i}from"convex/values";import{Cause as a,Context as o,Effect as s,Exit as c}from"effect";function l(e,l){return d=>{let f=typeof d==`function`?d:d.handler,p=async(e,...u)=>{let d=r(()=>l.services?l.services(e):o.empty()).pipe(s.flatMap(t=>r(()=>l.context?l.context(e):{}).pipe(s.flatMap(t=>s.sync(()=>{if(typeof t!=`object`||!t)throw Error(`Effect API context must be an object`);let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw Error(`Effect API context additions must be a plain record`);let r=e;for(let e of Reflect.ownKeys(t))if(e in r)throw Error(`Effect API context cannot replace ${String(e)}`);return l.context?Object.create(Object.getPrototypeOf(r),{...Object.getOwnPropertyDescriptors(r),...Object.getOwnPropertyDescriptors(t)}):e})),s.flatMap(e=>r(()=>f(e,...u))),s.provideContext(t)))),p=await s.runPromiseExit(s.scoped(d));if(c.isSuccess(p))return p.value;let m=p.cause.reasons.length===1?p.cause.reasons[0]:void 0;throw m&&a.isDieReason(m)&&t(p.cause)?m.defect:l.errors?new i(n(l.errors,p.cause)):m&&a.isFailReason(m)?l.mapError?l.mapError(m.error):m.error:m&&a.isDieReason(m)?m.defect:Error(`Effect API execution failed`,{cause:p.cause})};return e(typeof d==`function`?p:u(d,p))}}function u(t,n){let r={handler:n};for(let n of Reflect.ownKeys(t)){let i=Object.getOwnPropertyDescriptor(t,n);n!==`handler`&&i?.enumerable&&Object.defineProperty(r,n,{configurable:!0,enumerable:!0,...i.get?{get:e(()=>i.get.call(t))}:{value:i.value,writable:!0}})}return r}export{l as wrapEffectBuilder};
2
+ //# sourceMappingURL=api-runtime.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-runtime.mjs","names":["wrapEffectBuilder","original","definition","handler","args","program","normalizeEffect","options","ctx","Context","Effect","added","additionsPrototype","originalContext","key","context","services","exit","Exit","reason","Cause","getArgumentRejection","ConvexError","projectErrorCause","builder","withHandler","copy","descriptor","memoize"],"sources":["../../../src/modules/effect/api-runtime.ts"],"sourcesContent":["import { Cause, Context, Effect, Exit } from 'effect'\nimport type { Scope } from 'effect'\nimport { ConvexError, type Value } from 'convex/values'\nimport type { ErrorContract, ErrorDefinitions } from '../contracts/errors'\nimport { memoize } from '../contracts/lazy'\nimport { getArgumentRejection, projectErrorCause } from './errors'\nimport { normalizeEffect } from './normalize'\nimport type { CallbackRequirements, EffectValue } from './operation'\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Projection receives any expected failure and its result is always thrown, never returned as public data.\nexport type EffectApiErrorProjection = (error: unknown) => unknown\nexport type EffectApiErrorContract = Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\nexport type EffectApiHandlerValue<Value> =\n\t| Value\n\t| PromiseLike<Value>\n\t| Effect.Effect<Value, unknown, unknown>\n\nexport type EffectApiServices =\n\t| Context.Context<never>\n\t| PromiseLike<Context.Context<never>>\n\t| Effect.Effect<Context.Context<never>, unknown, Scope.Scope>\nexport type ProvidedServices<Provider> =\n\tEffectValue<Provider> extends Context.Context<infer Services> ? Services : never\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- This inference constraint requires record-shaped additions; each adapter preserves its concrete inferred fields and runtime checks the record boundary.\nexport type EffectApiContext = EffectApiHandlerValue<Record<string, unknown>>\ntype KeysOfUnion<Value> = Value extends object ? keyof Value : never\nexport type CheckedContext<Ctx, Added> =\n\tExtract<KeysOfUnion<EffectValue<Added>>, keyof Ctx> extends never ? unknown : never\nexport type EffectApiOptions<Ctx, Provider extends EffectApiServices, Added = {}> = (\n\t[ProvidedServices<Provider>] extends [never]\n\t\t? { services?: (ctx: Ctx) => Provider }\n\t\t: { services: (ctx: Ctx) => Provider }\n) & (\n\t[KeysOfUnion<EffectValue<Added>>] extends [never]\n\t\t? { context?: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n\t\t: { context: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n) & (\n\t| { errors: EffectApiErrorContract; mapError?: never }\n\t| { errors?: never; mapError?: EffectApiErrorProjection }\n)\nexport type CheckedApiRequirements<Returned, Provider> = [\n\tExclude<CallbackRequirements<NoInfer<Returned>>, ProvidedServices<Provider> | Scope.Scope>,\n] extends [never]\n\t? unknown\n\t: never\n\n/** Internal erasure is limited to the registration boundary; public adapters check A/E/R. */\nexport function wrapEffectBuilder(\n\tbuilder: Function,\n\toptions: {\n\t\tservices?: Function\n\t\tcontext?: Function\n\t\tmapError?: EffectApiErrorProjection\n\t\terrors?: EffectApiErrorContract\n\t},\n): Function {\n\treturn (definition: Function | { handler: Function }) => {\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Native registration explicitly accepts a callable or an object with a handler.\n\t\tconst original = typeof definition === 'function' ? definition : definition.handler\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Private erased callback receives the context already constructed by the checked native/custom builder.\n\t\tconst handler = async (ctx: unknown, ...args: unknown[]) => {\n\t\t\tconst program = normalizeEffect(() =>\n\t\t\t\toptions.services ? options.services(ctx) : Context.empty(),\n\t\t\t).pipe(\n\t\t\t\tEffect.flatMap((services) =>\n\t\t\t\t\tnormalizeEffect(() => (options.context ? options.context(ctx) : {})).pipe(\n\t\t\t\t\t\tEffect.flatMap((added) =>\n\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate erased context additions before enumerating or merging their fields.\n\t\t\t\t\t\t\t\tif (added === null || typeof added !== 'object')\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context must be an object')\n\t\t\t\t\t\t\t\tconst additionsPrototype = Object.getPrototypeOf(added)\n\t\t\t\t\t\t\t\tif (additionsPrototype !== Object.prototype && additionsPrototype !== null)\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context additions must be a plain record')\n\t\t\t\t\t\t\t\t// SAFETY: native and custom builders construct an object context before invoking this private handler.\n\t\t\t\t\t\t\t\tconst originalContext = ctx as object\n\t\t\t\t\t\t\t\tfor (const key of Reflect.ownKeys(added)) {\n\t\t\t\t\t\t\t\t\tif (key in originalContext)\n\t\t\t\t\t\t\t\t\t\tthrow Error(`Effect API context cannot replace ${String(key)}`)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn options.context\n\t\t\t\t\t\t\t\t\t? Object.create(Object.getPrototypeOf(originalContext), {\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(originalContext),\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(added),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t: ctx\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tEffect.flatMap((context) => normalizeEffect(() => original(context, ...args))),\n\t\t\t\t\t\tEffect.provideContext(services),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t)\n\t\t\t// SAFETY: checked public signatures prohibit unprovided handler requirements and\n\t\t\t// permit only Scope in providers; services are constructed within this same scope.\n\t\t\tconst exit = await Effect.runPromiseExit(\n\t\t\t\tEffect.scoped(program) as Effect.Effect<unknown, unknown>,\n\t\t\t)\n\t\t\tif (Exit.isSuccess(exit)) return exit.value\n\t\t\tconst reason = exit.cause.reasons.length === 1 ? exit.cause.reasons[0] : undefined\n\t\t\tif (reason && Cause.isDieReason(reason) && getArgumentRejection(exit.cause))\n\t\t\t\tthrow reason.defect\n\t\t\tif (options.errors) {\n\t\t\t\t// SAFETY: declared projection copies validated JSON-safe fields; all other Causes have a fixed safe envelope.\n\t\t\t\tthrow new ConvexError(projectErrorCause(options.errors, exit.cause) as Value)\n\t\t\t}\n\t\t\tif (reason && Cause.isFailReason(reason)) {\n\t\t\t\tthrow options.mapError ? options.mapError(reason.error) : reason.error\n\t\t\t}\n\t\t\tif (reason && Cause.isDieReason(reason)) throw reason.defect\n\t\t\tthrow new Error('Effect API execution failed', { cause: exit.cause })\n\t\t}\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Preserve the original native callable or object registration form.\n\t\treturn builder(typeof definition === 'function' ? handler : withHandler(definition, handler))\n\t}\n}\n\n/**\n * Object-spread equivalent that forwards accessors instead of reading them, so\n * getter-declared args and returns stay unread until the builder needs them.\n */\nfunction withHandler(definition: { handler: Function }, handler: Function) {\n\tconst copy = { handler }\n\tfor (const key of Reflect.ownKeys(definition)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(definition, key)\n\t\tif (key === 'handler' || !descriptor?.enumerable) continue\n\t\tObject.defineProperty(copy, key, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: true,\n\t\t\t...(descriptor.get\n\t\t\t\t? { get: memoize(() => descriptor.get!.call(definition)) }\n\t\t\t\t: { value: descriptor.value, writable: true }),\n\t\t})\n\t}\n\treturn copy\n}\n"],"mappings":"A,2RAgDA,SAAgBA,EACf,EACA,EAMW,CACX,MAAQ,IAAiD,CAExD,IAAMC,EAAW,OAAOC,GAAe,WAAaA,EAAaA,EAAW,QAEtEC,EAAU,MAAO,EAAc,GAAGC,IAAoB,CAC3D,IAAMC,EAAUC,MACfC,EAAQ,SAAWA,EAAQ,SAASC,CAAG,EAAIC,EAAQ,MAAM,CAC1D,CAAC,CAAC,KACDC,EAAO,QAAS,GACfJ,MAAuBC,EAAQ,QAAUA,EAAQ,QAAQC,CAAG,EAAI,CAAC,CAAE,CAAC,CAAC,KACpEE,EAAO,QAAS,GACfA,EAAO,SAAW,CAEjB,GAAsB,OAAOC,GAAU,WAAnCA,EACH,MAAM,MAAM,sCAAsC,EACnD,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,GAAIC,IAAuB,OAAO,WAAaA,IAAuB,KACrE,MAAM,MAAM,qDAAqD,EAElE,IAAMC,EAAkBL,EACxB,IAAK,IAAMM,KAAO,QAAQ,QAAQH,CAAK,EACtC,GAAIG,KAAOD,EACV,MAAM,MAAM,qCAAqC,OAAOC,CAAG,GAAG,EAEhE,OAAOP,EAAQ,QACZ,OAAO,OAAO,OAAO,eAAeM,CAAe,EAAG,CACtD,GAAG,OAAO,0BAA0BA,CAAe,EACnD,GAAG,OAAO,0BAA0BF,CAAK,CAC1C,CAAC,EACAH,CACJ,CAAC,CACF,EACAE,EAAO,QAAS,GAAYJ,MAAsBL,EAASc,EAAS,GAAGX,CAAI,CAAC,CAAC,EAC7EM,EAAO,eAAeM,CAAQ,CAC/B,CACD,CACD,EAGMC,EAAO,MAAMP,EAAO,eACzBA,EAAO,OAAOL,CAAO,CACtB,EACA,GAAIa,EAAK,UAAUD,CAAI,EAAG,OAAOA,EAAK,MACtC,IAAME,EAASF,EAAK,MAAM,QAAQ,SAAW,EAAIA,EAAK,MAAM,QAAQ,GAAK,IAAA,GAWzE,MAVIE,GAAUC,EAAM,YAAYD,CAAM,GAAKE,EAAqBJ,EAAK,KAAK,EACnEE,EAAO,OACVZ,EAAQ,OAEL,IAAIe,EAAYC,EAAkBhB,EAAQ,OAAQU,EAAK,KAAK,CAAU,EAEzEE,GAAUC,EAAM,aAAaD,CAAM,EAChCZ,EAAQ,SAAWA,EAAQ,SAASY,EAAO,KAAK,EAAIA,EAAO,MAE9DA,GAAUC,EAAM,YAAYD,CAAM,EAASA,EAAO,OAC5C,MAAM,8BAA+B,CAAE,MAAOF,EAAK,KAAM,CAAC,CACrE,EAEA,OAAOO,EAAQ,OAAOtB,GAAe,WAAaC,EAAUsB,EAAYvB,EAAYC,CAAO,CAAC,CAC7F,CACD,CAMA,SAASsB,EAAY,EAAmC,EAAmB,CAC1E,IAAMC,EAAO,CAAE,SAAQ,EACvB,IAAK,IAAMZ,KAAO,QAAQ,QAAQZ,CAAU,EAAG,CAC9C,IAAMyB,EAAa,OAAO,yBAAyBzB,EAAYY,CAAG,EAC9DA,IAAQ,WAAca,GAAY,YACtC,OAAO,eAAeD,EAAMZ,EAAK,CAChC,aAAc,GACd,WAAY,GACZ,GAAIa,EAAW,IACZ,CAAE,IAAKC,MAAcD,EAAW,IAAK,KAAKzB,CAAU,CAAC,CAAE,EACvD,CAAE,MAAOyB,EAAW,MAAO,SAAU,EAAK,CAC9C,CAAC,CACF,CACA,OAAOD,CACR,C"}
@@ -0,0 +1,46 @@
1
+ import { KType } from "../../k/types.mjs";
2
+ import { KArgs, KArgsInput, KArgsOutput, KCustomBuilder, KReturns } from "../../registration.mjs";
3
+ import { EffectApiContext, EffectApiHandlerValue, EffectApiOptions, EffectApiServices, ProvidedServices } from "./api-runtime.mjs";
4
+ import { CallbackRequirements, EffectValue } from "./operation.mjs";
5
+ import { GenericValidator, Infer, ObjectType, PropertyValidators } from "convex/values";
6
+ import { ActionBuilder, ArgsArrayToObject, DefaultFunctionArgs, FunctionVisibility, GenericActionCtx, GenericDataModel, GenericMutationCtx, GenericQueryCtx, MutationBuilder, QueryBuilder } from "convex/server";
7
+ import { Registration } from "convex-helpers/server/customFunctions";
8
+ import { Scope } from "effect";
9
+ type Expand<Value> = { [Key in keyof Value]: Value[Key]; };
10
+ type Overwrite<Input, Custom> = keyof Custom extends never ? Input : Omit<Input, keyof Custom> & Custom;
11
+ type HandlerArgs<Args, Made> = [Args] extends [void] ? Made extends Record<string, never> ? [DefaultFunctionArgs] : [Expand<DefaultFunctionArgs & Made>] : Made extends Record<string, never> ? [KArgsOutput<Args>] : [Expand<KArgsOutput<Args> & Made>];
12
+ /** A handler without declared args may still annotate its own (Convex's native rule). */
13
+ type HandlerArgsBound<Args, Made> = HandlerArgs<Args, Made> | ([Args] extends [void] ? (Made extends Record<string, never> ? [] : never) : never);
14
+ type RawArgs<Args, Custom extends PropertyValidators, OneOrZeroArgs extends [] | [DefaultFunctionArgs]> = [Args] extends [void] ? Custom extends Record<string, never> ? ArgsArrayToObject<OneOrZeroArgs> : Expand<DefaultFunctionArgs & ObjectType<Custom>> : Custom extends Record<string, never> ? KArgsInput<Args> : Expand<KArgsInput<Args> & ObjectType<Custom>>;
15
+ /** The value a handler must produce: the output side of a `k` schema, which Convex validates. */
16
+ type ResultValue<Returns> = [Returns] extends [KType] ? Returns['_output'] : [Returns] extends [GenericValidator] ? Infer<Returns> : unknown;
17
+ /**
18
+ * The registered result: what the handler returns when that already satisfies `returns` (so a
19
+ * narrower handler value, such as a search page's required `paginationMode`, reaches callers, as
20
+ * the `k` custom builders do), and the `returns` output otherwise.
21
+ */
22
+ type ResultOutput<Returns, Returned> = [Returns] extends [void] ? EffectValue<Returned> : [EffectValue<Returned>] extends [ResultValue<Returns>] ? EffectValue<Returned> : ResultValue<Returns>;
23
+ type CheckedRequirements<Returned, Services> = [Exclude<CallbackRequirements<NoInfer<Returned>>, Services | Scope.Scope>] extends [never] ? unknown : never;
24
+ type Reserved = 'args' | 'returns' | 'handler' | 'skipConvexValidation';
25
+ /**
26
+ * One Effect builder over a native Convex builder or a `k` custom builder (`kCustomQuery`, the auth
27
+ * constructors): `args` and `returns` accept `k` schemas and native validators, and the customization's
28
+ * context, made args and extra options are retained.
29
+ */
30
+ export type EffectApiBuilder<Kind extends 'query' | 'mutation' | 'action', CustomArgs extends PropertyValidators, CustomCtx extends object, CustomMadeArgs extends Record<string, unknown>, InputCtx, Visibility extends FunctionVisibility, ExtraArgs extends Record<string, unknown>, Services, Added = {}, Initialized = {}> = {
31
+ <Args extends KArgs | void = void, Returns extends KReturns | void = void, Returned extends EffectApiHandlerValue<ResultValue<Returns> | (null extends ResultValue<Returns> ? undefined | void : never)> = EffectApiHandlerValue<ResultValue<Returns> | (null extends ResultValue<Returns> ? undefined | void : never)>, OneOrZeroArgs extends HandlerArgsBound<Args, CustomMadeArgs> = HandlerArgs<Args, CustomMadeArgs>>(definition: (({
32
+ args?: Args;
33
+ returns?: Returns;
34
+ /** Export no validators to Convex; the kit then parses args fully itself (KTD3). */
35
+ skipConvexValidation?: boolean;
36
+ handler: (ctx: Overwrite<InputCtx, CustomCtx> & Added, ...args: OneOrZeroArgs) => Returned;
37
+ } & Omit<ExtraArgs, Reserved>) | ((ctx: Overwrite<InputCtx, CustomCtx> & Added, ...args: OneOrZeroArgs) => Returned)) & CheckedRequirements<Returned, Services> & CheckedRequirements<Initialized, Services>): Registration<Kind, Visibility, RawArgs<Args, CustomArgs, Extract<OneOrZeroArgs, [] | [DefaultFunctionArgs]>>, ResultOutput<Returns, Returned>>;
38
+ };
39
+ type Adapter<Kind extends 'query' | 'mutation' | 'action', Ctx, Visibility extends FunctionVisibility, Provider, Added> = EffectApiBuilder<Kind, {}, {}, {}, Ctx, Visibility, {}, ProvidedServices<Provider>, EffectValue<Added>, Added>;
40
+ /** Provision request services after the supplied builder has constructed its trusted context. */
41
+ export declare function effectApiBuilder<Kind extends 'query' | 'mutation' | 'action', CustomArgs extends PropertyValidators, CustomCtx extends Record<string, any>, CustomMadeArgs extends Record<string, any>, InputCtx, Visibility extends FunctionVisibility, ExtraArgs extends Record<string, any>, Provider extends EffectApiServices = import('effect').Context.Context<never>, Added extends EffectApiContext = {}>(builder: KCustomBuilder<Kind, CustomArgs, CustomCtx, CustomMadeArgs, InputCtx, Visibility, ExtraArgs>, options: EffectApiOptions<Overwrite<InputCtx, CustomCtx>, Provider, Added>): EffectApiBuilder<Kind, CustomArgs, CustomCtx, CustomMadeArgs, InputCtx, Visibility, ExtraArgs, ProvidedServices<Provider>, EffectValue<Added>, Added>;
42
+ export declare function effectApiBuilder<DM extends GenericDataModel, V extends FunctionVisibility, Provider extends EffectApiServices = import('effect').Context.Context<never>, Added extends EffectApiContext = {}>(builder: QueryBuilder<DM, V>, options: EffectApiOptions<GenericQueryCtx<DM>, Provider, Added>): Adapter<'query', GenericQueryCtx<DM>, V, Provider, Added>;
43
+ export declare function effectApiBuilder<DM extends GenericDataModel, V extends FunctionVisibility, Provider extends EffectApiServices = import('effect').Context.Context<never>, Added extends EffectApiContext = {}>(builder: MutationBuilder<DM, V>, options: EffectApiOptions<GenericMutationCtx<DM>, Provider, Added>): Adapter<'mutation', GenericMutationCtx<DM>, V, Provider, Added>;
44
+ export declare function effectApiBuilder<DM extends GenericDataModel, V extends FunctionVisibility, Provider extends EffectApiServices = import('effect').Context.Context<never>, Added extends EffectApiContext = {}>(builder: ActionBuilder<DM, V>, options: EffectApiOptions<GenericActionCtx<DM>, Provider, Added>): Adapter<'action', GenericActionCtx<DM>, V, Provider, Added>;
45
+ export {};
46
+ //# sourceMappingURL=api.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{kCustomQuery as e}from"../../registration.mjs";import{wrapEffectBuilder as t}from"./api-runtime.mjs";import{actionGeneric as n,internalActionGeneric as r,internalMutationGeneric as i,internalQueryGeneric as a,mutationGeneric as o,queryGeneric as s}from"convex/server";import{NoOp as c}from"convex-helpers/server/customFunctions";function l(e,n){return t(u.has(e)?d(e):e,n)}const u=/* @__PURE__ */ new Set([s,o,n,a,i,r]);function d(t){return e(t,c)}export{l as effectApiBuilder};
2
+ //# sourceMappingURL=api.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.mjs","names":["effectApiBuilder","wrapEffectBuilder","nativeBuilders","builder","kBuilder","options","queryGeneric","mutationGeneric","actionGeneric","internalQueryGeneric","internalMutationGeneric","internalActionGeneric","kCustomQuery","NoOp"],"sources":["../../../src/modules/effect/api.ts"],"sourcesContent":["import {\n\tactionGeneric,\n\tinternalActionGeneric,\n\tinternalMutationGeneric,\n\tinternalQueryGeneric,\n\tmutationGeneric,\n\tqueryGeneric,\n\ttype ActionBuilder,\n\ttype ArgsArrayToObject,\n\ttype DefaultFunctionArgs,\n\ttype FunctionVisibility,\n\ttype GenericActionCtx,\n\ttype GenericDataModel,\n\ttype GenericMutationCtx,\n\ttype GenericQueryCtx,\n\ttype MutationBuilder,\n\ttype QueryBuilder,\n} from 'convex/server'\nimport type { GenericValidator, Infer, ObjectType, PropertyValidators } from 'convex/values'\nimport { NoOp, type Registration } from 'convex-helpers/server/customFunctions'\nimport type { Scope } from 'effect'\nimport type { KType } from '../../k/types'\nimport {\n\tkCustomQuery,\n\ttype KArgs,\n\ttype KArgsInput,\n\ttype KArgsOutput,\n\ttype KCustomBuilder,\n\ttype KReturns,\n} from '../../registration'\nimport {\n\twrapEffectBuilder,\n\ttype EffectApiOptions,\n\ttype EffectApiErrorProjection,\n\ttype EffectApiErrorContract,\n\ttype EffectApiServices,\n\ttype EffectApiHandlerValue,\n\ttype EffectApiContext,\n\ttype ProvidedServices,\n} from './api-runtime'\nimport type { CallbackRequirements, EffectValue } from './operation'\n\n// The argument and result grammar of src/registration.ts: `k` schemas, native validators, or both.\ntype Expand<Value> = { [Key in keyof Value]: Value[Key] }\ntype Overwrite<Input, Custom> = keyof Custom extends never\n\t? Input\n\t: Omit<Input, keyof Custom> & Custom\ntype HandlerArgs<Args, Made> = [Args] extends [void]\n\t? Made extends Record<string, never>\n\t\t? [DefaultFunctionArgs]\n\t\t: [Expand<DefaultFunctionArgs & Made>]\n\t: Made extends Record<string, never>\n\t\t? [KArgsOutput<Args>]\n\t\t: [Expand<KArgsOutput<Args> & Made>]\n/** A handler without declared args may still annotate its own (Convex's native rule). */\ntype HandlerArgsBound<Args, Made> =\n\t| HandlerArgs<Args, Made>\n\t| ([Args] extends [void] ? (Made extends Record<string, never> ? [] : never) : never)\ntype RawArgs<\n\tArgs,\n\tCustom extends PropertyValidators,\n\tOneOrZeroArgs extends [] | [DefaultFunctionArgs],\n> = [Args] extends [void]\n\t? Custom extends Record<string, never>\n\t\t? ArgsArrayToObject<OneOrZeroArgs>\n\t\t: Expand<DefaultFunctionArgs & ObjectType<Custom>>\n\t: Custom extends Record<string, never>\n\t\t? KArgsInput<Args>\n\t\t: Expand<KArgsInput<Args> & ObjectType<Custom>>\n/** The value a handler must produce: the output side of a `k` schema, which Convex validates. */\ntype ResultValue<Returns> = [Returns] extends [KType]\n\t? Returns['_output']\n\t: [Returns] extends [GenericValidator]\n\t\t? Infer<Returns>\n\t\t: unknown\n/**\n * The registered result: what the handler returns when that already satisfies `returns` (so a\n * narrower handler value, such as a search page's required `paginationMode`, reaches callers, as\n * the `k` custom builders do), and the `returns` output otherwise.\n */\ntype ResultOutput<Returns, Returned> = [Returns] extends [void]\n\t? EffectValue<Returned>\n\t: [EffectValue<Returned>] extends [ResultValue<Returns>]\n\t\t? EffectValue<Returned>\n\t\t: ResultValue<Returns>\ntype CheckedRequirements<Returned, Services> = [\n\tExclude<CallbackRequirements<NoInfer<Returned>>, Services | Scope.Scope>,\n] extends [never]\n\t? unknown\n\t: never\ntype Reserved = 'args' | 'returns' | 'handler' | 'skipConvexValidation'\n\n/**\n * One Effect builder over a native Convex builder or a `k` custom builder (`kCustomQuery`, the auth\n * constructors): `args` and `returns` accept `k` schemas and native validators, and the customization's\n * context, made args and extra options are retained.\n */\nexport type EffectApiBuilder<\n\tKind extends 'query' | 'mutation' | 'action',\n\tCustomArgs extends PropertyValidators,\n\t// Native Convex context interfaces do not declare a string index signature.\n\tCustomCtx extends object,\n\tCustomMadeArgs extends Record<string, unknown>,\n\tInputCtx,\n\tVisibility extends FunctionVisibility,\n\tExtraArgs extends Record<string, unknown>,\n\tServices,\n\tAdded = {},\n\tInitialized = {},\n> = {\n\t<\n\t\tArgs extends KArgs | void = void,\n\t\tReturns extends KReturns | void = void,\n\t\tReturned extends EffectApiHandlerValue<\n\t\t\tResultValue<Returns> | (null extends ResultValue<Returns> ? undefined | void : never)\n\t\t> = EffectApiHandlerValue<\n\t\t\tResultValue<Returns> | (null extends ResultValue<Returns> ? undefined | void : never)\n\t\t>,\n\t\tOneOrZeroArgs extends HandlerArgsBound<Args, CustomMadeArgs> = HandlerArgs<\n\t\t\tArgs,\n\t\t\tCustomMadeArgs\n\t\t>,\n\t>(\n\t\tdefinition: (\n\t\t\t| ({\n\t\t\t\t\targs?: Args\n\t\t\t\t\treturns?: Returns\n\t\t\t\t\t/** Export no validators to Convex; the kit then parses args fully itself (KTD3). */\n\t\t\t\t\tskipConvexValidation?: boolean\n\t\t\t\t\thandler: (ctx: Overwrite<InputCtx, CustomCtx> & Added, ...args: OneOrZeroArgs) => Returned\n\t\t\t } & Omit<ExtraArgs, Reserved>)\n\t\t\t| ((ctx: Overwrite<InputCtx, CustomCtx> & Added, ...args: OneOrZeroArgs) => Returned)\n\t\t) &\n\t\t\tCheckedRequirements<Returned, Services> &\n\t\t\tCheckedRequirements<Initialized, Services>,\n\t): Registration<\n\t\tKind,\n\t\tVisibility,\n\t\tRawArgs<Args, CustomArgs, Extract<OneOrZeroArgs, [] | [DefaultFunctionArgs]>>,\n\t\tResultOutput<Returns, Returned>\n\t>\n}\n\ntype Adapter<\n\tKind extends 'query' | 'mutation' | 'action',\n\tCtx,\n\tVisibility extends FunctionVisibility,\n\tProvider,\n\tAdded,\n> = EffectApiBuilder<\n\tKind,\n\t{},\n\t{},\n\t{},\n\tCtx,\n\tVisibility,\n\t{},\n\tProvidedServices<Provider>,\n\tEffectValue<Added>,\n\tAdded\n>\n\n/** Provision request services after the supplied builder has constructed its trusted context. */\nexport function effectApiBuilder<\n\tKind extends 'query' | 'mutation' | 'action',\n\tCustomArgs extends PropertyValidators,\n\tCustomCtx extends Record<string, any>,\n\tCustomMadeArgs extends Record<string, any>,\n\tInputCtx,\n\tVisibility extends FunctionVisibility,\n\tExtraArgs extends Record<string, any>,\n\tProvider extends EffectApiServices = import('effect').Context.Context<never>,\n\tAdded extends EffectApiContext = {},\n>(\n\tbuilder: KCustomBuilder<\n\t\tKind,\n\t\tCustomArgs,\n\t\tCustomCtx,\n\t\tCustomMadeArgs,\n\t\tInputCtx,\n\t\tVisibility,\n\t\tExtraArgs\n\t>,\n\toptions: EffectApiOptions<Overwrite<InputCtx, CustomCtx>, Provider, Added>,\n): EffectApiBuilder<\n\tKind,\n\tCustomArgs,\n\tCustomCtx,\n\tCustomMadeArgs,\n\tInputCtx,\n\tVisibility,\n\tExtraArgs,\n\tProvidedServices<Provider>,\n\tEffectValue<Added>,\n\tAdded\n>\nexport function effectApiBuilder<\n\tDM extends GenericDataModel,\n\tV extends FunctionVisibility,\n\tProvider extends EffectApiServices = import('effect').Context.Context<never>,\n\tAdded extends EffectApiContext = {},\n>(\n\tbuilder: QueryBuilder<DM, V>,\n\toptions: EffectApiOptions<GenericQueryCtx<DM>, Provider, Added>,\n): Adapter<'query', GenericQueryCtx<DM>, V, Provider, Added>\nexport function effectApiBuilder<\n\tDM extends GenericDataModel,\n\tV extends FunctionVisibility,\n\tProvider extends EffectApiServices = import('effect').Context.Context<never>,\n\tAdded extends EffectApiContext = {},\n>(\n\tbuilder: MutationBuilder<DM, V>,\n\toptions: EffectApiOptions<GenericMutationCtx<DM>, Provider, Added>,\n): Adapter<'mutation', GenericMutationCtx<DM>, V, Provider, Added>\nexport function effectApiBuilder<\n\tDM extends GenericDataModel,\n\tV extends FunctionVisibility,\n\tProvider extends EffectApiServices = import('effect').Context.Context<never>,\n\tAdded extends EffectApiContext = {},\n>(\n\tbuilder: ActionBuilder<DM, V>,\n\toptions: EffectApiOptions<GenericActionCtx<DM>, Provider, Added>,\n): Adapter<'action', GenericActionCtx<DM>, V, Provider, Added>\nexport function effectApiBuilder(\n\tbuilder: Function,\n\toptions: {\n\t\tservices?: Function\n\t\tcontext?: Function\n\t\tmapError?: EffectApiErrorProjection\n\t\terrors?: EffectApiErrorContract\n\t},\n): Function {\n\treturn wrapEffectBuilder(nativeBuilders.has(builder) ? kBuilder(builder) : builder, options)\n}\n\n/**\n * Convex's own registration functions; every generated `query`/`mutation`/`action` is one of them.\n * Any other builder is a `k` custom builder, which already accepts `k` schemas and must not be\n * wrapped twice (its made args would reach the outer parse).\n */\nconst nativeBuilders = new Set<Function>([\n\tqueryGeneric,\n\tmutationGeneric,\n\tactionGeneric,\n\tinternalQueryGeneric,\n\tinternalMutationGeneric,\n\tinternalActionGeneric,\n])\n\n/** A native builder behind src/registration.ts with no customization, so it accepts `k` schemas. */\nfunction kBuilder(builder: Function): Function {\n\t// SAFETY: kCustomQuery, kCustomMutation and kCustomAction share one kind-agnostic runtime; the kind\n\t// is a type-level label only, and the public overloads above carry the native builder's own kind.\n\treturn kCustomQuery(builder as QueryBuilder<GenericDataModel, FunctionVisibility>, NoOp)\n}\n"],"mappings":"A,gVA+NA,SAAgBA,EACf,EACA,EAMW,CACX,OAAOC,EAAkBC,EAAe,IAAIC,CAAO,EAAIC,EAASD,CAAO,EAAIA,EAASE,CAAO,CAC5F,CAOA,MAAMH,kBAAiB,IAAI,IAAc,CACxCI,EACAC,EACAC,EACAC,EACAC,EACAC,CACD,CAAC,EAGD,SAASP,EAAS,EAA6B,CAG9C,OAAOQ,EAAaT,EAA+DU,CAAI,CACxF,C"}
@@ -0,0 +1,46 @@
1
+ import { AuthBundle, AuthFunctions, AuthFunctionsConfig, DefaultRole, Include, ServiceMutation, ServicePrincipal, ServiceQuery } from "../../auth.mjs";
2
+ import { KCustomBuilder } from "../../registration.mjs";
3
+ import { EffectApiBuilder } from "./api.mjs";
4
+ import { EffectApiContext, EffectApiOptions, EffectApiServices, ProvidedServices } from "./api-runtime.mjs";
5
+ import { EffectValue } from "./operation.mjs";
6
+ import { GenericActionCtx, GenericDataModel, GenericMutationCtx, GenericQueryCtx } from "convex/server";
7
+ import { Context } from "effect";
8
+ type Adapted<Builder, Services, Added> = Builder extends KCustomBuilder<infer Kind, infer Args, infer Ctx, infer Made, infer Input, infer Visibility, infer Extra> ? EffectApiBuilder<Kind, Args, Ctx, Made, Input, Visibility, Extra, ProvidedServices<Services>, EffectValue<Added>, Added> : never;
9
+ /** Shared post-auth composition; internal/system policies are configured separately. */
10
+ export type EffectAuthFunctions<DataModel extends GenericDataModel, Role extends string = DefaultRole, QueryServices extends EffectApiServices = Context.Context<never>, QueryAdded extends EffectApiContext = {}, MutationServices extends EffectApiServices = Context.Context<never>, MutationAdded extends EffectApiContext = {}, ActionServices extends EffectApiServices = Context.Context<never>, ActionAdded extends EffectApiContext = {}, SystemQueryServices extends EffectApiServices = Context.Context<never>, SystemQueryAdded extends EffectApiContext = {}, SystemMutationServices extends EffectApiServices = Context.Context<never>, SystemMutationAdded extends EffectApiContext = {}, SystemActionServices extends EffectApiServices = Context.Context<never>, SystemActionAdded extends EffectApiContext = {}> = Pick<AuthFunctions<DataModel, Role>, 'include' | 'authenticatedUser'> & {
11
+ authQuery: Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>;
12
+ roleQuery: (...allowed: readonly Role[]) => Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>;
13
+ adminQuery: Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>;
14
+ authMutation: Adapted<AuthFunctions<DataModel, Role>['authMutation'], MutationServices, MutationAdded>;
15
+ roleMutation: (...allowed: readonly Role[]) => Adapted<AuthFunctions<DataModel, Role>['authMutation'], MutationServices, MutationAdded>;
16
+ adminMutation: Adapted<AuthFunctions<DataModel, Role>['authMutation'], MutationServices, MutationAdded>;
17
+ authAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>;
18
+ roleAction: (...allowed: readonly Role[]) => Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>;
19
+ adminAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>;
20
+ /** Service principals share the `query` policy; the host factory is the only principal source. */
21
+ serviceQuery: <Extra extends Record<string, unknown> = {}>(principal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>) => Adapted<ServiceQuery<DataModel, Role, Extra>, QueryServices, QueryAdded>;
22
+ /** Service principals share the `mutation` policy. */
23
+ serviceMutation: <Extra extends Record<string, unknown> = {}>(principal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>) => Adapted<ServiceMutation<DataModel, Role, Extra>, MutationServices, MutationAdded>;
24
+ systemQuery: Adapted<AuthFunctions<DataModel, Role>['systemQuery'], SystemQueryServices, SystemQueryAdded>;
25
+ systemMutation: Adapted<AuthFunctions<DataModel, Role>['systemMutation'], SystemMutationServices, SystemMutationAdded>;
26
+ systemAction: Adapted<AuthFunctions<DataModel, Role>['systemAction'], SystemActionServices, SystemActionAdded>;
27
+ };
28
+ /** Providers and handles run once per invocation after security and live role checks. */
29
+ export declare function createEffectAuthFunctions<DataModel extends GenericDataModel, const Role extends string = DefaultRole, QueryServices extends EffectApiServices = Context.Context<never>, QueryAdded extends EffectApiContext = {}, MutationServices extends EffectApiServices = Context.Context<never>, MutationAdded extends EffectApiContext = {}, ActionServices extends EffectApiServices = Context.Context<never>, ActionAdded extends EffectApiContext = {}, SystemQueryServices extends EffectApiServices = Context.Context<never>, SystemQueryAdded extends EffectApiContext = {}, SystemMutationServices extends EffectApiServices = Context.Context<never>, SystemMutationAdded extends EffectApiContext = {}, SystemActionServices extends EffectApiServices = Context.Context<never>, SystemActionAdded extends EffectApiContext = {}>(config: AuthFunctionsConfig<DataModel, Role>, options: {
30
+ query: EffectApiOptions<GenericQueryCtx<DataModel> & AuthBundle<Role> & {
31
+ include: Include;
32
+ }, QueryServices, QueryAdded>;
33
+ mutation: EffectApiOptions<GenericMutationCtx<DataModel> & AuthBundle<Role> & {
34
+ include: Include;
35
+ }, MutationServices, MutationAdded>;
36
+ action: EffectApiOptions<GenericActionCtx<DataModel> & AuthBundle<Role>, ActionServices, ActionAdded>;
37
+ systemQuery: EffectApiOptions<GenericQueryCtx<DataModel> & {
38
+ include: Include;
39
+ }, SystemQueryServices, SystemQueryAdded>;
40
+ systemMutation: EffectApiOptions<GenericMutationCtx<DataModel> & {
41
+ include: Include;
42
+ }, SystemMutationServices, SystemMutationAdded>;
43
+ systemAction: EffectApiOptions<GenericActionCtx<DataModel>, SystemActionServices, SystemActionAdded>;
44
+ }): EffectAuthFunctions<DataModel, Role, QueryServices, QueryAdded, MutationServices, MutationAdded, ActionServices, ActionAdded, SystemQueryServices, SystemQueryAdded, SystemMutationServices, SystemMutationAdded, SystemActionServices, SystemActionAdded>;
45
+ export {};
46
+ //# sourceMappingURL=auth.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{createAuthFunctions as e}from"../../auth.mjs";import{effectApiBuilder as t}from"./api.mjs";import{wrapEffectBuilder as n}from"./api-runtime.mjs";function r(n,r){let a=e(n);return{include:a.include,authenticatedUser:a.authenticatedUser,authQuery:t(a.authQuery,r.query),roleQuery:(...e)=>t(a.roleQuery(...e),r.query),adminQuery:t(a.adminQuery,r.query),authMutation:t(a.authMutation,r.mutation),roleMutation:(...e)=>t(a.roleMutation(...e),r.mutation),adminMutation:t(a.adminMutation,r.mutation),authAction:t(a.authAction,r.action),roleAction:(...e)=>t(a.roleAction(...e),r.action),adminAction:t(a.adminAction,r.action),serviceQuery:e=>i(a.serviceQuery(e),r.query),serviceMutation:e=>i(a.serviceMutation(e),r.mutation),systemQuery:t(a.systemQuery,r.systemQuery),systemMutation:t(a.systemMutation,r.systemMutation),systemAction:t(a.systemAction,r.systemAction)}}function i(e,t){return n(e,t)}export{r as createEffectAuthFunctions};
2
+ //# sourceMappingURL=auth.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.mjs","names":["createEffectAuthFunctions","auth","createAuthFunctions","config","effectApiBuilder","options","allowed","adaptService","principal","wrapEffectBuilder","builder"],"sources":["../../../src/modules/effect/auth.ts"],"sourcesContent":["import type { Context } from 'effect'\nimport type {\n\tGenericDataModel,\n\tGenericQueryCtx,\n\tGenericMutationCtx,\n\tGenericActionCtx,\n} from 'convex/server'\nimport {\n\tcreateAuthFunctions,\n\ttype AuthFunctions,\n\ttype AuthFunctionsConfig,\n\ttype AuthBundle,\n\ttype DefaultRole,\n\ttype Include,\n\ttype ServicePrincipal,\n\ttype ServiceQuery,\n\ttype ServiceMutation,\n} from '../../auth'\nimport type { KCustomBuilder } from '../../registration'\nimport { effectApiBuilder, type EffectApiBuilder } from './api'\nimport {\n\twrapEffectBuilder,\n\ttype EffectApiOptions,\n\ttype EffectApiServices,\n\ttype EffectApiContext,\n\ttype ProvidedServices,\n} from './api-runtime'\nimport type { EffectValue } from './operation'\n\n// Derive the adapter from the symbolic auth contract, never from inferred native spreads.\ntype Adapted<Builder, Services, Added> =\n\tBuilder extends KCustomBuilder<\n\t\tinfer Kind,\n\t\tinfer Args,\n\t\tinfer Ctx,\n\t\tinfer Made,\n\t\tinfer Input,\n\t\tinfer Visibility,\n\t\tinfer Extra\n\t>\n\t\t? EffectApiBuilder<\n\t\t\t\tKind,\n\t\t\t\tArgs,\n\t\t\t\tCtx,\n\t\t\t\tMade,\n\t\t\t\tInput,\n\t\t\t\tVisibility,\n\t\t\t\tExtra,\n\t\t\t\tProvidedServices<Services>,\n\t\t\t\tEffectValue<Added>,\n\t\t\t\tAdded\n\t\t\t>\n\t\t: never\n\n/** Shared post-auth composition; internal/system policies are configured separately. */\nexport type EffectAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tRole extends string = DefaultRole,\n\tQueryServices extends EffectApiServices = Context.Context<never>,\n\tQueryAdded extends EffectApiContext = {},\n\tMutationServices extends EffectApiServices = Context.Context<never>,\n\tMutationAdded extends EffectApiContext = {},\n\tActionServices extends EffectApiServices = Context.Context<never>,\n\tActionAdded extends EffectApiContext = {},\n\tSystemQueryServices extends EffectApiServices = Context.Context<never>,\n\tSystemQueryAdded extends EffectApiContext = {},\n\tSystemMutationServices extends EffectApiServices = Context.Context<never>,\n\tSystemMutationAdded extends EffectApiContext = {},\n\tSystemActionServices extends EffectApiServices = Context.Context<never>,\n\tSystemActionAdded extends EffectApiContext = {},\n> = Pick<AuthFunctions<DataModel, Role>, 'include' | 'authenticatedUser'> & {\n\tauthQuery: Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>\n\troleQuery: (\n\t\t...allowed: readonly Role[]\n\t) => Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>\n\tadminQuery: Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>\n\tauthMutation: Adapted<\n\t\tAuthFunctions<DataModel, Role>['authMutation'],\n\t\tMutationServices,\n\t\tMutationAdded\n\t>\n\troleMutation: (\n\t\t...allowed: readonly Role[]\n\t) => Adapted<AuthFunctions<DataModel, Role>['authMutation'], MutationServices, MutationAdded>\n\tadminMutation: Adapted<\n\t\tAuthFunctions<DataModel, Role>['authMutation'],\n\t\tMutationServices,\n\t\tMutationAdded\n\t>\n\tauthAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>\n\troleAction: (\n\t\t...allowed: readonly Role[]\n\t) => Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>\n\tadminAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>\n\t/** Service principals share the `query` policy; the host factory is the only principal source. */\n\tserviceQuery: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t) => Adapted<ServiceQuery<DataModel, Role, Extra>, QueryServices, QueryAdded>\n\t/** Service principals share the `mutation` policy. */\n\tserviceMutation: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t) => Adapted<ServiceMutation<DataModel, Role, Extra>, MutationServices, MutationAdded>\n\tsystemQuery: Adapted<\n\t\tAuthFunctions<DataModel, Role>['systemQuery'],\n\t\tSystemQueryServices,\n\t\tSystemQueryAdded\n\t>\n\tsystemMutation: Adapted<\n\t\tAuthFunctions<DataModel, Role>['systemMutation'],\n\t\tSystemMutationServices,\n\t\tSystemMutationAdded\n\t>\n\tsystemAction: Adapted<\n\t\tAuthFunctions<DataModel, Role>['systemAction'],\n\t\tSystemActionServices,\n\t\tSystemActionAdded\n\t>\n}\n\n/** Providers and handles run once per invocation after security and live role checks. */\nexport function createEffectAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n\tQueryServices extends EffectApiServices = Context.Context<never>,\n\tQueryAdded extends EffectApiContext = {},\n\tMutationServices extends EffectApiServices = Context.Context<never>,\n\tMutationAdded extends EffectApiContext = {},\n\tActionServices extends EffectApiServices = Context.Context<never>,\n\tActionAdded extends EffectApiContext = {},\n\tSystemQueryServices extends EffectApiServices = Context.Context<never>,\n\tSystemQueryAdded extends EffectApiContext = {},\n\tSystemMutationServices extends EffectApiServices = Context.Context<never>,\n\tSystemMutationAdded extends EffectApiContext = {},\n\tSystemActionServices extends EffectApiServices = Context.Context<never>,\n\tSystemActionAdded extends EffectApiContext = {},\n>(\n\tconfig: AuthFunctionsConfig<DataModel, Role>,\n\toptions: {\n\t\tquery: EffectApiOptions<\n\t\t\tGenericQueryCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t\tQueryServices,\n\t\t\tQueryAdded\n\t\t>\n\t\tmutation: EffectApiOptions<\n\t\t\tGenericMutationCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t\tMutationServices,\n\t\t\tMutationAdded\n\t\t>\n\t\taction: EffectApiOptions<\n\t\t\tGenericActionCtx<DataModel> & AuthBundle<Role>,\n\t\t\tActionServices,\n\t\t\tActionAdded\n\t\t>\n\t\tsystemQuery: EffectApiOptions<\n\t\t\tGenericQueryCtx<DataModel> & { include: Include },\n\t\t\tSystemQueryServices,\n\t\t\tSystemQueryAdded\n\t\t>\n\t\tsystemMutation: EffectApiOptions<\n\t\t\tGenericMutationCtx<DataModel> & { include: Include },\n\t\t\tSystemMutationServices,\n\t\t\tSystemMutationAdded\n\t\t>\n\t\tsystemAction: EffectApiOptions<\n\t\t\tGenericActionCtx<DataModel>,\n\t\t\tSystemActionServices,\n\t\t\tSystemActionAdded\n\t\t>\n\t},\n): EffectAuthFunctions<\n\tDataModel,\n\tRole,\n\tQueryServices,\n\tQueryAdded,\n\tMutationServices,\n\tMutationAdded,\n\tActionServices,\n\tActionAdded,\n\tSystemQueryServices,\n\tSystemQueryAdded,\n\tSystemMutationServices,\n\tSystemMutationAdded,\n\tSystemActionServices,\n\tSystemActionAdded\n> {\n\tconst auth = createAuthFunctions(config)\n\treturn {\n\t\tinclude: auth.include,\n\t\tauthenticatedUser: auth.authenticatedUser,\n\t\tauthQuery: effectApiBuilder(auth.authQuery, options.query),\n\t\troleQuery: (...allowed) => effectApiBuilder(auth.roleQuery(...allowed), options.query),\n\t\tadminQuery: effectApiBuilder(auth.adminQuery, options.query),\n\t\tauthMutation: effectApiBuilder(auth.authMutation, options.mutation),\n\t\troleMutation: (...allowed) => effectApiBuilder(auth.roleMutation(...allowed), options.mutation),\n\t\tadminMutation: effectApiBuilder(auth.adminMutation, options.mutation),\n\t\tauthAction: effectApiBuilder(auth.authAction, options.action),\n\t\troleAction: (...allowed) => effectApiBuilder(auth.roleAction(...allowed), options.action),\n\t\tadminAction: effectApiBuilder(auth.adminAction, options.action),\n\t\tserviceQuery: <Extra extends Record<string, unknown> = {}>(\n\t\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t\t) =>\n\t\t\tadaptService<ServiceQuery<DataModel, Role, Extra>, QueryServices, QueryAdded>(\n\t\t\t\tauth.serviceQuery(principal),\n\t\t\t\toptions.query,\n\t\t\t),\n\t\tserviceMutation: <Extra extends Record<string, unknown> = {}>(\n\t\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t\t) =>\n\t\t\tadaptService<ServiceMutation<DataModel, Role, Extra>, MutationServices, MutationAdded>(\n\t\t\t\tauth.serviceMutation(principal),\n\t\t\t\toptions.mutation,\n\t\t\t),\n\t\tsystemQuery: effectApiBuilder(auth.systemQuery, options.systemQuery),\n\t\tsystemMutation: effectApiBuilder(auth.systemMutation, options.systemMutation),\n\t\tsystemAction: effectApiBuilder(auth.systemAction, options.systemAction),\n\t}\n}\n\n/** Service builders reuse the query/mutation policy; the ctx adds only host extras. */\nfunction adaptService<Builder extends Function, Services extends EffectApiServices, Added>(\n\tbuilder: Builder,\n\toptions: Parameters<typeof wrapEffectBuilder>[1],\n): Adapted<Builder, Services, Added> {\n\t// SAFETY: the shared policy callbacks read only the standard auth bundle, which every\n\t// service ctx carries; wrapEffectBuilder swaps the handler and keeps the builder's\n\t// registration kind, validation and visibility, as effectApiBuilder does.\n\treturn wrapEffectBuilder(builder, options) as Adapted<Builder, Services, Added>\n}\n"],"mappings":"A,wJAwHA,SAAgBA,EAgBf,EACA,EA+CC,CACD,IAAMC,EAAOC,EAAoBC,CAAM,EACvC,MAAO,CACN,QAASF,EAAK,QACd,kBAAmBA,EAAK,kBACxB,UAAWG,EAAiBH,EAAK,UAAWI,EAAQ,KAAK,EACzD,WAAY,GAAGC,IAAYF,EAAiBH,EAAK,UAAU,GAAGK,CAAO,EAAGD,EAAQ,KAAK,EACrF,WAAYD,EAAiBH,EAAK,WAAYI,EAAQ,KAAK,EAC3D,aAAcD,EAAiBH,EAAK,aAAcI,EAAQ,QAAQ,EAClE,cAAe,GAAGC,IAAYF,EAAiBH,EAAK,aAAa,GAAGK,CAAO,EAAGD,EAAQ,QAAQ,EAC9F,cAAeD,EAAiBH,EAAK,cAAeI,EAAQ,QAAQ,EACpE,WAAYD,EAAiBH,EAAK,WAAYI,EAAQ,MAAM,EAC5D,YAAa,GAAGC,IAAYF,EAAiBH,EAAK,WAAW,GAAGK,CAAO,EAAGD,EAAQ,MAAM,EACxF,YAAaD,EAAiBH,EAAK,YAAaI,EAAQ,MAAM,EAC9D,aACC,GAEAE,EACCN,EAAK,aAAaO,CAAS,EAC3BH,EAAQ,KACT,EACD,gBACC,GAEAE,EACCN,EAAK,gBAAgBO,CAAS,EAC9BH,EAAQ,QACT,EACD,YAAaD,EAAiBH,EAAK,YAAaI,EAAQ,WAAW,EACnE,eAAgBD,EAAiBH,EAAK,eAAgBI,EAAQ,cAAc,EAC5E,aAAcD,EAAiBH,EAAK,aAAcI,EAAQ,YAAY,CACvE,CACD,CAGA,SAASE,EACR,EACA,EACoC,CAIpC,OAAOE,EAAkBC,EAASL,CAAO,CAC1C,C"}
@@ -0,0 +1,15 @@
1
+ import { OperationExecutor, OperationPublicResult, OperationTool, OperationToolConverter, OperationToolDefinition, OperationToolJsonSchema, OperationToolOutcome, SelectedOperation, bindOperationExecutor, createOperationTools, operationToolDialect, selectOperation } from "../contracts/exposure.mjs";
2
+ import "./agent-tools.mjs";
3
+ import { CallbackError, CallbackRequirements, EffectMiddlewareInput, EffectOperationArgument, EffectOperationError, EffectOperationHandlerResult, EffectOperationInput, EffectOperationRequirements, EffectOperationResult, EffectPreparation, EffectValue, effectOperationFactory } from "./operation.mjs";
4
+ import { EffectFoundationOptions, createEffectFoundation } from "./foundation.mjs";
5
+ import { ActionAuditWriterError, EffectActionDependencies, EffectActionRegistry } from "./action.mjs";
6
+ import { EffectIdempotencyPreparation, effectTransactionalIdempotency } from "./idempotency.mjs";
7
+ import { EffectCrudConfig, EffectCrudContext, EffectCrudPage, EffectCrudPagination, EffectCrudRepository, EffectCrudTable, createEffectCrud } from "./crud.mjs";
8
+ import { EffectApiBuilder, effectApiBuilder } from "./api.mjs";
9
+ import { projectErrorCause } from "./errors.mjs";
10
+ import { EffectErrors, effectErrors } from "./failures.mjs";
11
+ import { FailureAuditEntry, FailureAuditOptions } from "./failure-audit.mjs";
12
+ import { NestedAuditMode, RequestScope } from "./scope.mjs";
13
+ import { ContractDecoderError, ContractDecoderRequirements, ContractValidationError, EffectDecoder, decodeEffectContract, effectContract, effectSchema, effectStandardSchema } from "./schema.mjs";
14
+ import { EffectReceiptProtectedWorkflowMutation, effectReceiptWorkflowMutation, effectTerminalWorkflowAttempt, effectWorkflowAttempt, effectWorkflowStatusBindings } from "./workflow.mjs";
15
+ export { ActionAuditWriterError, type CallbackError, type CallbackRequirements, type ContractDecoderError, type ContractDecoderRequirements, ContractValidationError, type EffectActionDependencies, type EffectActionRegistry, type EffectApiBuilder, type EffectCrudConfig, type EffectCrudContext, type EffectCrudPage, type EffectCrudPagination, type EffectCrudRepository, type EffectCrudTable, type EffectDecoder, type EffectErrors, type EffectFoundationOptions, type EffectIdempotencyPreparation, type EffectMiddlewareInput, type EffectOperationArgument, type EffectOperationError, type EffectOperationHandlerResult, type EffectOperationInput, type EffectOperationRequirements, type EffectOperationResult, type EffectPreparation, type EffectReceiptProtectedWorkflowMutation, type EffectValue, type FailureAuditEntry, type FailureAuditOptions, type NestedAuditMode, type OperationExecutor, type OperationPublicResult, type OperationTool, type OperationToolConverter, type OperationToolDefinition, type OperationToolJsonSchema, type OperationToolOutcome, type RequestScope, type SelectedOperation, bindOperationExecutor, createEffectCrud, createEffectFoundation, createOperationTools, decodeEffectContract, effectApiBuilder, effectContract, effectErrors, effectOperationFactory, effectReceiptWorkflowMutation, effectSchema, effectStandardSchema, effectTerminalWorkflowAttempt, effectTransactionalIdempotency, effectWorkflowAttempt, effectWorkflowStatusBindings, operationToolDialect, projectErrorCause, selectOperation };
@@ -0,0 +1 @@
1
+ import{bindOperationExecutor as e,createOperationTools as t,operationToolDialect as n,selectOperation as r}from"../contracts/exposure.mjs";import{effectOperationFactory as i}from"./operation.mjs";import{createEffectFoundation as a}from"./foundation.mjs";import{ActionAuditWriterError as o}from"./action.mjs";import{effectTransactionalIdempotency as s}from"./idempotency.mjs";import{createEffectCrud as c}from"./crud.mjs";import{effectApiBuilder as l}from"./api.mjs";import{projectErrorCause as u}from"./errors.mjs";import{effectErrors as d}from"./failures.mjs";import{ContractValidationError as f,decodeEffectContract as p,effectContract as m,effectSchema as h,effectStandardSchema as g}from"./schema.mjs";import{effectReceiptWorkflowMutation as _,effectTerminalWorkflowAttempt as v,effectWorkflowAttempt as y,effectWorkflowStatusBindings as b}from"./workflow.mjs";export{o as ActionAuditWriterError,f as ContractValidationError,e as bindOperationExecutor,c as createEffectCrud,a as createEffectFoundation,t as createOperationTools,p as decodeEffectContract,l as effectApiBuilder,m as effectContract,d as effectErrors,i as effectOperationFactory,_ as effectReceiptWorkflowMutation,h as effectSchema,g as effectStandardSchema,v as effectTerminalWorkflowAttempt,s as effectTransactionalIdempotency,y as effectWorkflowAttempt,b as effectWorkflowStatusBindings,n as operationToolDialect,u as projectErrorCause,r as selectOperation};
@@ -0,0 +1,108 @@
1
+ import { ContractOutput, ContractSchema } from "../contracts/contract.mjs";
2
+ import { AuditEntryInput } from "../../components/foundation/client.mjs";
3
+ import { ArgumentFailurePolicy } from "../contracts/errors.mjs";
4
+ import { OperationPublicResult, SelectedOperation } from "../contracts/exposure.mjs";
5
+ import { Observability } from "../../components/foundation/modules/observability/observability.mjs";
6
+ import { FailureAuditOptions } from "./failure-audit.mjs";
7
+ import { NestedAuditMode, RequestScope } from "./scope.mjs";
8
+ import { CallbackError, CallbackRequirements, CheckedEffectOperation, EffectOperationArgument, EffectOperationError, EffectOperationRequirements, EffectOperationResult, EffectValue, UnwrappedDefaultError, UnwrappedDefaultRequirements, ValidatedEffectOperations, effectOperationFactory } from "./operation.mjs";
9
+ import { DomainAuditInput, DomainCommandContract, DomainContract } from "../contracts/domain.mjs";
10
+ import { BoundOperations } from "../contracts/binding.mjs";
11
+ import { AuditValue, AuditedOperations, DomainEffectFactory, DomainEffectImplementations, ExactDomainOperations, SharedEffectFactory } from "./domain.mjs";
12
+ import { Effect } from "effect";
13
+ type Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>;
14
+ type Callback = (...arguments_: never[]) => Supported<unknown>;
15
+ export type Resolver = (host: never) => Supported<unknown>;
16
+ export type HostOf<Resolve extends Resolver> = Parameters<Resolve>[0];
17
+ export type DomainOf<Resolve extends Resolver> = EffectValue<ReturnType<Resolve>>;
18
+ type Operation = {
19
+ input: ContractSchema;
20
+ result: ContractSchema;
21
+ classification: string;
22
+ handler: Callback;
23
+ audit: Callback;
24
+ guard?: Callback;
25
+ prepare?: Callback;
26
+ middleware?: Callback;
27
+ permission?: string;
28
+ aggregates?: readonly string[];
29
+ replayResult?: ContractSchema;
30
+ };
31
+ export type Registry<Context> = Readonly<Record<string, Pick<Operation, 'input' | 'result' | 'handler'> & Partial<Pick<Operation, 'classification' | 'audit'>> & CheckedEffectOperation<Context>>>;
32
+ export type EffectCommandDependencies = {
33
+ observability: Observability;
34
+ checkPermission?: (host: never, input: {
35
+ permission: string;
36
+ operation: string;
37
+ }) => Supported<void>;
38
+ writeAudit: (host: never, entry: AuditEntryInput) => Supported<unknown>;
39
+ /** `fold` (default): an operation nested under an auditing operation leaves the audit to it. */
40
+ nestedAudit?: NestedAuditMode;
41
+ /** Host-free sink for failed operations; see `FailureAuditOptions`. */
42
+ auditFailure?: FailureAuditOptions;
43
+ /** How command input validation failures are thrown. */
44
+ argumentFailure?: ArgumentFailurePolicy;
45
+ };
46
+ export type HostParameter<Policy> = [Exclude<Policy, undefined>] extends [never] ? unknown : Exclude<Policy, undefined> extends ((...arguments_: infer Arguments) => Supported<unknown>) ? Arguments extends [] ? unknown : Arguments[0] : unknown;
47
+ type PolicyHost<Dependencies extends EffectCommandDependencies> = HostParameter<Dependencies['writeAudit']> & HostParameter<Dependencies['checkPermission']>;
48
+ type HostCompatible<Resolve extends Resolver, Dependencies extends EffectCommandDependencies> = [HostOf<Resolve>] extends [PolicyHost<Dependencies>] ? unknown : {
49
+ context: never;
50
+ };
51
+ type Factory<Resolve extends Resolver, Guard> = ReturnType<typeof effectOperationFactory<DomainOf<Resolve>, Record<never, never>, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>>>;
52
+ export type EffectCommandConfiguration<Resolve extends Resolver, Operations extends Registry<DomainOf<Resolve>>, Guard> = {
53
+ context: Resolve;
54
+ operations: (define: Factory<Resolve, Guard>) => Operations & NoInfer<ValidatedEffectOperations<Operations>>;
55
+ defaults?: {
56
+ guard?: (context: DomainOf<Resolve>) => Guard;
57
+ };
58
+ };
59
+ type ErrorOf<Definition, Resolve, Dependencies, Guard> = EffectOperationError<Definition> | CallbackError<Resolve | Dependencies[keyof Dependencies]> | UnwrappedDefaultError<Definition, Guard>;
60
+ type RequirementsOf<Definition, Resolve, Dependencies, Guard> = EffectOperationRequirements<Definition> | CallbackRequirements<Resolve | Dependencies[keyof Dependencies]> | UnwrappedDefaultRequirements<Definition, Guard>;
61
+ /** Internal registry constructor: the public Foundation binds host policies once. */
62
+ export declare function createEffectCommand<Resolve extends Resolver, const Operations extends Registry<DomainOf<Resolve>>, const Dependencies extends EffectCommandDependencies, Guard = never>(configuration: EffectCommandConfiguration<Resolve, Operations, Guard> & Dependencies & HostCompatible<Resolve, Dependencies>): {
63
+ /** Bind invocation context without resolving it or running an operation. */
64
+ withContext(context: HostOf<Resolve>): {
65
+ exec: <Key extends Extract<keyof Operations, string>>(operation: Key, input: EffectOperationArgument<Operations[Key]>) => Effect.Effect<ContractOutput<Operations[Key]["result"]>, ErrorOf<Operations[Key], Resolve, Dependencies, Guard>, RequirementsOf<Operations[Key], Resolve, Dependencies, Guard>>;
66
+ };
67
+ expose<const Owner extends symbol, const Key extends Extract<keyof Operations, string>>(owner: Owner, operation: Key): SelectedOperation<Owner, Key, Operations[Key]['input'], OperationPublicResult<Operations[Key]>>;
68
+ exec: <Key extends Extract<keyof Operations, string>>(operation: Key, input: EffectOperationArgument<Operations[Key]>, host: HostOf<Resolve>) => Effect.Effect<EffectOperationResult<Operations[Key]>, ErrorOf<Operations[Key], Resolve, Dependencies, Guard>, RequirementsOf<Operations[Key], Resolve, Dependencies, Guard>>;
69
+ };
70
+ /** Bind trusted application policies without exposing a loose public command kernel. */
71
+ export declare function bindEffectCommand<const Dependencies extends EffectCommandDependencies>(dependencies: Dependencies): {
72
+ <Resolve extends Resolver, const Contract extends DomainContract & {
73
+ commands: Readonly<Record<string, DomainCommandContract>>;
74
+ }, const Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['commands'], true>, Mode extends true, Guard = never>(configuration: {
75
+ contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['commands']> & ValidatedEffectOperations<Operations> ? unknown : never>;
76
+ context: Resolve;
77
+ audit?: never;
78
+ operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], Mode, never, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>, Contract['errors']>) => Operations;
79
+ defaults?: {
80
+ guard?: (context: DomainOf<Resolve>) => Guard;
81
+ };
82
+ } & HostCompatible<Resolve, Dependencies>): ReturnType<typeof createEffectCommand<Resolve, BoundOperations<Operations, Contract['commands']> & { [Key in keyof Contract['commands']]: {
83
+ classification: Contract['commands'][Key]['classification'];
84
+ audit: Operations[Key]['audit'];
85
+ }; }, Dependencies, Guard>>;
86
+ <Resolve extends Resolver, const Contract extends DomainContract & {
87
+ commands: Readonly<Record<string, DomainCommandContract>>;
88
+ }, const Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['commands']>, Returned extends AuditValue, Guard = never>(configuration: {
89
+ contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['commands']> & ValidatedEffectOperations<Operations> ? unknown : never>;
90
+ context: Resolve;
91
+ audit: (resolution: DomainAuditInput<Contract['commands']>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
92
+ operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], true, [Returned] extends [never] ? never : (resolution: never, context: never) => Returned, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>, Contract['errors']>) => Operations;
93
+ defaults?: {
94
+ guard?: (context: DomainOf<Resolve>) => Guard;
95
+ };
96
+ } & HostCompatible<Resolve, Dependencies>): ReturnType<typeof createEffectCommand<Resolve, AuditedOperations<BoundOperations<Operations, Contract['commands']>, (resolution: never, context: never) => Returned>, Dependencies, Guard>>;
97
+ <Resolve extends Resolver, const Operations extends Readonly<Record<string, Pick<Operation, "classification" | "handler" | "input" | "result"> & CheckedEffectOperation<EffectValue<ReturnType<Resolve>>>>>, Returned extends AuditValue, Guard>(configuration: {
98
+ context: Resolve;
99
+ audit: (resolution: DomainAuditInput<Operations>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
100
+ operations: (define: SharedEffectFactory<DomainOf<Resolve>, Guard>) => Operations & NoInfer<ValidatedEffectOperations<Operations>>;
101
+ defaults?: {
102
+ guard?: (context: DomainOf<Resolve>) => Guard;
103
+ };
104
+ } & HostCompatible<Resolve, Dependencies>): ReturnType<typeof createEffectCommand<Resolve, AuditedOperations<Operations, (resolution: never, context: never) => Returned>, Dependencies, Guard>>;
105
+ <Resolve extends Resolver, const Operations extends Registry<DomainOf<Resolve>>, Guard = never>(configuration: EffectCommandConfiguration<Resolve, Operations, Guard> & HostCompatible<Resolve, Dependencies>): ReturnType<typeof createEffectCommand<Resolve, Operations, Dependencies, Guard>>;
106
+ };
107
+ export {};
108
+ //# sourceMappingURL=command.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{memoize as e,registerLazyRegistry as t}from"../contracts/lazy.mjs";import{decodeOperationInput as n}from"./input.mjs";import{selectOperation as r}from"../contracts/exposure.mjs";import{decodeEffectContract as i}from"./schema.mjs";import{CommandPermissionError as a,executeCommandLifecycle as o}from"../../components/foundation/modules/command/lifecycle.mjs";import{normalizeEffect as s,observationFailure as c}from"./normalize.mjs";import{reportAuditWriteFailure as l,reportFailure as u}from"./failure-audit.mjs";import{auditFolded as d,enterRequestScope as f}from"./scope.mjs";import{effectOperationFactory as p}from"./operation.mjs";import{snapshotOperations as m}from"../contracts/binding.mjs";import{domainEffectFactory as h}from"./domain.mjs";import{Cause as g,Effect as _,Exit as v}from"effect";const y={succeed:_.succeed,suspend:_.suspend,flatMap:_.flatMap};function b(m){let h=e(()=>m.operations(p())),b=m,x=b.mode??`command`,C=(e,t,r)=>_.suspend(()=>{let p=h();if(!Object.prototype.hasOwnProperty.call(p,e))throw Error(`The selected command operation is not configured`);let C=p[e],w=C.classification??x,T=n(C.input,t,m.argumentFailure,m.auditFailure,{kind:x,operation:e,classification:w});return _.flatMap(T,t=>{let n=t,p=C.audit,h=m.observability.start({operation:e,classification:w}),T=m.context;return f(e,p!==void 0,(t,f)=>s(()=>T(r)).pipe(_.flatMap(c=>o(y,{operation:e,classification:w,context:c,command:n,permission:C.permission===void 0?void 0:()=>s(()=>{if(!m.checkPermission)throw new a(e);return m.checkPermission(r,{permission:C.permission,operation:e})}).pipe(_.asVoid),prepare:()=>s(()=>C.prepare?.(c,n)).pipe(_.map(e=>e?.kind===`execute`?{kind:`execute`,complete:e.complete?t=>s(()=>e.complete(t)).pipe(_.asVoid):void 0}:e)),decodeReplay:e=>i(C.replayResult??C.result,e),middleware:C.middleware?[e=>S(()=>C.middleware({...e,input:n}))]:[],defaultGuard:e=>s(()=>m.defaults?.guard?.(e)).pipe(_.asVoid),guard:e=>s(()=>C.guard?.(e,n)).pipe(_.asVoid),run:e=>S(()=>C.handler(n,e)),decodeResult:e=>i(C.result,e),audit:e=>!p||x!==`action`&&d(m.nestedAudit,t)?_.succeed(null):s(()=>p({command:n,result:e},c,t?.scope)),writeAudit:n=>{let i=s(()=>m.writeAudit(r,n));return x===`action`?i.pipe(_.catchCause(n=>g.hasInterrupts(n)?_.failCause(n):l(m.auditFailure,{operation:e,classification:w,entered:t}))):i},aggregates:C.aggregates})),_.onExit(r=>_.sync(()=>{v.isSuccess(r)?h.completed():h.failed(c(r.cause))}).pipe(_.andThen(u(m.auditFailure,r,{kind:x,operation:e,classification:w,input:n,get contract(){return b.contract?.errors},entered:t,current:f}))))))})});return t({withContext(e){return{exec:(t,n)=>C(t,n,e)}},expose(e,t){let n=h();if(!Object.hasOwn(n,t))throw Error(`The selected command operation is not configured`);return r(e,`mutation`,t,n[t])},exec:C},h)}function x(e){function t(t){let n=()=>{let e=t.contract?h(t.contract.commands??{},!0,t.contract.errors):p();return m(t.operations(e),t.contract,`commands`,t.audit)};return b({...t,...e,operations:n})}return t}function S(e){return s(e)}export{x as bindEffectCommand,b as createEffectCommand};
2
+ //# sourceMappingURL=command.mjs.map