@yielded/auth-persistence-drizzle 0.1.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 (401) hide show
  1. package/README.md +17 -0
  2. package/dist/D1.d.mts +963 -0
  3. package/dist/D1.mjs +29 -0
  4. package/dist/D1.mjs.map +1 -0
  5. package/dist/Libsql.d.mts +2134 -0
  6. package/dist/Libsql.mjs +77 -0
  7. package/dist/Libsql.mjs.map +1 -0
  8. package/dist/Mysql2.d.mts +1817 -0
  9. package/dist/Mysql2.mjs +55 -0
  10. package/dist/Mysql2.mjs.map +1 -0
  11. package/dist/Pglite.d.mts +1821 -0
  12. package/dist/Pglite.mjs +53 -0
  13. package/dist/Pglite.mjs.map +1 -0
  14. package/dist/Postgres.d.mts +1821 -0
  15. package/dist/Postgres.mjs +53 -0
  16. package/dist/Postgres.mjs.map +1 -0
  17. package/dist/SqliteBun.d.mts +2129 -0
  18. package/dist/SqliteBun.mjs +70 -0
  19. package/dist/SqliteBun.mjs.map +1 -0
  20. package/dist/SqliteDo.d.mts +2181 -0
  21. package/dist/SqliteDo.mjs +105 -0
  22. package/dist/SqliteDo.mjs.map +1 -0
  23. package/dist/SqliteNode.d.mts +2129 -0
  24. package/dist/SqliteNode.mjs +70 -0
  25. package/dist/SqliteNode.mjs.map +1 -0
  26. package/dist/SqliteWasm.d.mts +2132 -0
  27. package/dist/SqliteWasm.mjs +70 -0
  28. package/dist/SqliteWasm.mjs.map +1 -0
  29. package/dist/_virtual/_rolldown/runtime.mjs +13 -0
  30. package/dist/drizzle/D1BatchStatements.d.mts +10 -0
  31. package/dist/drizzle/D1BatchStatements.mjs +8 -0
  32. package/dist/drizzle/D1BatchStatements.mjs.map +1 -0
  33. package/dist/drizzle/SuppliedService.d.mts +9 -0
  34. package/dist/drizzle/d1-emails.d.mts +61 -0
  35. package/dist/drizzle/d1-emails.mjs +578 -0
  36. package/dist/drizzle/d1-emails.mjs.map +1 -0
  37. package/dist/drizzle/d1-generated-statement.mjs +79 -0
  38. package/dist/drizzle/d1-generated-statement.mjs.map +1 -0
  39. package/dist/drizzle/d1-identity.d.mts +30 -0
  40. package/dist/drizzle/d1-identity.mjs +118 -0
  41. package/dist/drizzle/d1-identity.mjs.map +1 -0
  42. package/dist/drizzle/d1-oauth.d.mts +300 -0
  43. package/dist/drizzle/d1-oauth.mjs +76 -0
  44. package/dist/drizzle/d1-oauth.mjs.map +1 -0
  45. package/dist/drizzle/d1-passkey.d.mts +47 -0
  46. package/dist/drizzle/d1-passkey.mjs +95 -0
  47. package/dist/drizzle/d1-passkey.mjs.map +1 -0
  48. package/dist/drizzle/d1-password-prepared.d.mts +24 -0
  49. package/dist/drizzle/d1-password-prepared.mjs +460 -0
  50. package/dist/drizzle/d1-password-prepared.mjs.map +1 -0
  51. package/dist/drizzle/d1-passwords.d.mts +86 -0
  52. package/dist/drizzle/d1-passwords.mjs +1003 -0
  53. package/dist/drizzle/d1-passwords.mjs.map +1 -0
  54. package/dist/drizzle/d1-phone.d.mts +23 -0
  55. package/dist/drizzle/d1-phone.mjs +30 -0
  56. package/dist/drizzle/d1-phone.mjs.map +1 -0
  57. package/dist/drizzle/d1-planning.d.mts +11 -0
  58. package/dist/drizzle/d1-planning.mjs +43 -0
  59. package/dist/drizzle/d1-planning.mjs.map +1 -0
  60. package/dist/drizzle/d1-proofs.d.mts +79 -0
  61. package/dist/drizzle/d1-proofs.mjs +829 -0
  62. package/dist/drizzle/d1-proofs.mjs.map +1 -0
  63. package/dist/drizzle/d1-sessions.d.mts +66 -0
  64. package/dist/drizzle/d1-sessions.mjs +965 -0
  65. package/dist/drizzle/d1-sessions.mjs.map +1 -0
  66. package/dist/drizzle/d1-totp.d.mts +23 -0
  67. package/dist/drizzle/d1-totp.mjs +27 -0
  68. package/dist/drizzle/d1-totp.mjs.map +1 -0
  69. package/dist/drizzle/email-model.d.mts +30 -0
  70. package/dist/drizzle/email-model.mjs +2 -0
  71. package/dist/drizzle/email-registration.d.mts +29 -0
  72. package/dist/drizzle/email-registration.mjs +236 -0
  73. package/dist/drizzle/email-registration.mjs.map +1 -0
  74. package/dist/drizzle/email-sql.d.mts +1 -0
  75. package/dist/drizzle/email-sql.mjs +9 -0
  76. package/dist/drizzle/email-sql.mjs.map +1 -0
  77. package/dist/drizzle/email-target.d.mts +19 -0
  78. package/dist/drizzle/email-target.mjs +72 -0
  79. package/dist/drizzle/email-target.mjs.map +1 -0
  80. package/dist/drizzle/model.d.mts +245 -0
  81. package/dist/drizzle/model.mjs +55 -0
  82. package/dist/drizzle/model.mjs.map +1 -0
  83. package/dist/drizzle/mysql-emails.d.mts +70 -0
  84. package/dist/drizzle/mysql-emails.mjs +38 -0
  85. package/dist/drizzle/mysql-emails.mjs.map +1 -0
  86. package/dist/drizzle/mysql-identity.d.mts +21 -0
  87. package/dist/drizzle/mysql-identity.mjs +93 -0
  88. package/dist/drizzle/mysql-identity.mjs.map +1 -0
  89. package/dist/drizzle/mysql-password-prepared.d.mts +29 -0
  90. package/dist/drizzle/mysql-password-prepared.mjs +16 -0
  91. package/dist/drizzle/mysql-password-prepared.mjs.map +1 -0
  92. package/dist/drizzle/mysql-passwords.d.mts +85 -0
  93. package/dist/drizzle/mysql-passwords.mjs +38 -0
  94. package/dist/drizzle/mysql-passwords.mjs.map +1 -0
  95. package/dist/drizzle/mysql-proofs.d.mts +74 -0
  96. package/dist/drizzle/mysql-proofs.mjs +23 -0
  97. package/dist/drizzle/mysql-proofs.mjs.map +1 -0
  98. package/dist/drizzle/mysql-sessions.d.mts +91 -0
  99. package/dist/drizzle/mysql-sessions.mjs +53 -0
  100. package/dist/drizzle/mysql-sessions.mjs.map +1 -0
  101. package/dist/drizzle/mysql.d.mts +69 -0
  102. package/dist/drizzle/mysql.mjs +218 -0
  103. package/dist/drizzle/mysql.mjs.map +1 -0
  104. package/dist/drizzle/oauth-accounts.mjs +358 -0
  105. package/dist/drizzle/oauth-accounts.mjs.map +1 -0
  106. package/dist/drizzle/oauth-connected-access.mjs +210 -0
  107. package/dist/drizzle/oauth-connected-access.mjs.map +1 -0
  108. package/dist/drizzle/oauth-connected-collection.mjs +202 -0
  109. package/dist/drizzle/oauth-connected-collection.mjs.map +1 -0
  110. package/dist/drizzle/oauth-connected-custody.mjs +146 -0
  111. package/dist/drizzle/oauth-connected-custody.mjs.map +1 -0
  112. package/dist/drizzle/oauth-connected-drivers.mjs +76 -0
  113. package/dist/drizzle/oauth-connected-drivers.mjs.map +1 -0
  114. package/dist/drizzle/oauth-connected-flow.mjs +247 -0
  115. package/dist/drizzle/oauth-connected-flow.mjs.map +1 -0
  116. package/dist/drizzle/oauth-connected-input.mjs +103 -0
  117. package/dist/drizzle/oauth-connected-input.mjs.map +1 -0
  118. package/dist/drizzle/oauth-connected-maintenance.mjs +214 -0
  119. package/dist/drizzle/oauth-connected-maintenance.mjs.map +1 -0
  120. package/dist/drizzle/oauth-connected-management.mjs +228 -0
  121. package/dist/drizzle/oauth-connected-management.mjs.map +1 -0
  122. package/dist/drizzle/oauth-connected-model.d.mts +277 -0
  123. package/dist/drizzle/oauth-connected-model.mjs +22 -0
  124. package/dist/drizzle/oauth-connected-model.mjs.map +1 -0
  125. package/dist/drizzle/oauth-connected-reference.d.mts +16 -0
  126. package/dist/drizzle/oauth-connected-reference.mjs +53 -0
  127. package/dist/drizzle/oauth-connected-reference.mjs.map +1 -0
  128. package/dist/drizzle/oauth-connected-settlement.mjs +117 -0
  129. package/dist/drizzle/oauth-connected-settlement.mjs.map +1 -0
  130. package/dist/drizzle/oauth-connected-state.d.mts +1954 -0
  131. package/dist/drizzle/oauth-connected-state.mjs +422 -0
  132. package/dist/drizzle/oauth-connected-state.mjs.map +1 -0
  133. package/dist/drizzle/oauth-connected-target.d.mts +752 -0
  134. package/dist/drizzle/oauth-connected-target.mjs +91 -0
  135. package/dist/drizzle/oauth-connected-target.mjs.map +1 -0
  136. package/dist/drizzle/oauth-drivers.mjs +51 -0
  137. package/dist/drizzle/oauth-drivers.mjs.map +1 -0
  138. package/dist/drizzle/oauth-flow.d.mts +22 -0
  139. package/dist/drizzle/oauth-flow.mjs +253 -0
  140. package/dist/drizzle/oauth-flow.mjs.map +1 -0
  141. package/dist/drizzle/oauth-input.mjs +127 -0
  142. package/dist/drizzle/oauth-input.mjs.map +1 -0
  143. package/dist/drizzle/oauth-model.d.mts +461 -0
  144. package/dist/drizzle/oauth-model.mjs +49 -0
  145. package/dist/drizzle/oauth-model.mjs.map +1 -0
  146. package/dist/drizzle/oauth-mysql.mjs +8 -0
  147. package/dist/drizzle/oauth-mysql.mjs.map +1 -0
  148. package/dist/drizzle/oauth-owner.d.mts +10 -0
  149. package/dist/drizzle/oauth-owner.mjs +10 -0
  150. package/dist/drizzle/oauth-owner.mjs.map +1 -0
  151. package/dist/drizzle/oauth-registration.d.mts +5 -0
  152. package/dist/drizzle/oauth-registration.mjs +374 -0
  153. package/dist/drizzle/oauth-registration.mjs.map +1 -0
  154. package/dist/drizzle/oauth-state.mjs +107 -0
  155. package/dist/drizzle/oauth-state.mjs.map +1 -0
  156. package/dist/drizzle/oauth-target.d.mts +109 -0
  157. package/dist/drizzle/oauth-target.mjs +246 -0
  158. package/dist/drizzle/oauth-target.mjs.map +1 -0
  159. package/dist/drizzle/passkey-drivers.mjs +34 -0
  160. package/dist/drizzle/passkey-drivers.mjs.map +1 -0
  161. package/dist/drizzle/passkey-kernel.mjs +8 -0
  162. package/dist/drizzle/passkey-kernel.mjs.map +1 -0
  163. package/dist/drizzle/passkey-model.d.mts +43 -0
  164. package/dist/drizzle/passkey-model.mjs +8 -0
  165. package/dist/drizzle/passkey-model.mjs.map +1 -0
  166. package/dist/drizzle/passkey-registration-ceremony-model.d.mts +12 -0
  167. package/dist/drizzle/passkey-registration-ceremony-model.mjs +2 -0
  168. package/dist/drizzle/passkey-state.mjs +7 -0
  169. package/dist/drizzle/passkey-state.mjs.map +1 -0
  170. package/dist/drizzle/passkey-target.d.mts +2 -0
  171. package/dist/drizzle/passkey-target.mjs +7 -0
  172. package/dist/drizzle/passkey-target.mjs.map +1 -0
  173. package/dist/drizzle/passkey-write-drivers.mjs +32 -0
  174. package/dist/drizzle/passkey-write-drivers.mjs.map +1 -0
  175. package/dist/drizzle/passkey-write-model.d.mts +20 -0
  176. package/dist/drizzle/passkey-write-model.mjs +9 -0
  177. package/dist/drizzle/passkey-write-model.mjs.map +1 -0
  178. package/dist/drizzle/passkey-write-target.d.mts +5 -0
  179. package/dist/drizzle/passkey-write-target.mjs +7 -0
  180. package/dist/drizzle/passkey-write-target.mjs.map +1 -0
  181. package/dist/drizzle/password-model.d.mts +24 -0
  182. package/dist/drizzle/password-model.mjs +2 -0
  183. package/dist/drizzle/password-prepared-model.d.mts +92 -0
  184. package/dist/drizzle/password-prepared-model.mjs +11 -0
  185. package/dist/drizzle/password-prepared-model.mjs.map +1 -0
  186. package/dist/drizzle/password-prepared-sql.mjs +389 -0
  187. package/dist/drizzle/password-prepared-sql.mjs.map +1 -0
  188. package/dist/drizzle/password-prepared-state.mjs +104 -0
  189. package/dist/drizzle/password-prepared-state.mjs.map +1 -0
  190. package/dist/drizzle/password-prepared-target.d.mts +11 -0
  191. package/dist/drizzle/password-prepared-target.mjs +56 -0
  192. package/dist/drizzle/password-prepared-target.mjs.map +1 -0
  193. package/dist/drizzle/password-registration.d.mts +7 -0
  194. package/dist/drizzle/password-registration.mjs +134 -0
  195. package/dist/drizzle/password-registration.mjs.map +1 -0
  196. package/dist/drizzle/password-sql.d.mts +1 -0
  197. package/dist/drizzle/password-sql.mjs +9 -0
  198. package/dist/drizzle/password-sql.mjs.map +1 -0
  199. package/dist/drizzle/password-target.d.mts +16 -0
  200. package/dist/drizzle/password-target.mjs +61 -0
  201. package/dist/drizzle/password-target.mjs.map +1 -0
  202. package/dist/drizzle/pg-emails.d.mts +71 -0
  203. package/dist/drizzle/pg-emails.mjs +38 -0
  204. package/dist/drizzle/pg-emails.mjs.map +1 -0
  205. package/dist/drizzle/pg-password-prepared.d.mts +30 -0
  206. package/dist/drizzle/pg-password-prepared.mjs +16 -0
  207. package/dist/drizzle/pg-password-prepared.mjs.map +1 -0
  208. package/dist/drizzle/pg-passwords.d.mts +86 -0
  209. package/dist/drizzle/pg-passwords.mjs +38 -0
  210. package/dist/drizzle/pg-passwords.mjs.map +1 -0
  211. package/dist/drizzle/pg-proofs.d.mts +75 -0
  212. package/dist/drizzle/pg-proofs.mjs +22 -0
  213. package/dist/drizzle/pg-proofs.mjs.map +1 -0
  214. package/dist/drizzle/pg-sessions.d.mts +92 -0
  215. package/dist/drizzle/pg-sessions.mjs +53 -0
  216. package/dist/drizzle/pg-sessions.mjs.map +1 -0
  217. package/dist/drizzle/pg.d.mts +80 -0
  218. package/dist/drizzle/pg.mjs +289 -0
  219. package/dist/drizzle/pg.mjs.map +1 -0
  220. package/dist/drizzle/phone-model.d.mts +113 -0
  221. package/dist/drizzle/phone-model.mjs +39 -0
  222. package/dist/drizzle/phone-model.mjs.map +1 -0
  223. package/dist/drizzle/phone-state.mjs +14 -0
  224. package/dist/drizzle/phone-state.mjs.map +1 -0
  225. package/dist/drizzle/phone-target.d.mts +14 -0
  226. package/dist/drizzle/phone-target.mjs +168 -0
  227. package/dist/drizzle/phone-target.mjs.map +1 -0
  228. package/dist/drizzle/proof-model.d.mts +21 -0
  229. package/dist/drizzle/proof-model.mjs +2 -0
  230. package/dist/drizzle/proof-sql.d.mts +1 -0
  231. package/dist/drizzle/proof-sql.mjs +8 -0
  232. package/dist/drizzle/proof-sql.mjs.map +1 -0
  233. package/dist/drizzle/proof-target.d.mts +11 -0
  234. package/dist/drizzle/proof-target.mjs +36 -0
  235. package/dist/drizzle/proof-target.mjs.map +1 -0
  236. package/dist/drizzle/query-operations.mjs +27 -0
  237. package/dist/drizzle/query-operations.mjs.map +1 -0
  238. package/dist/drizzle/session-model.d.mts +31 -0
  239. package/dist/drizzle/session-model.mjs +2 -0
  240. package/dist/drizzle/session-sql.mjs +8 -0
  241. package/dist/drizzle/session-sql.mjs.map +1 -0
  242. package/dist/drizzle/session-target.d.mts +27 -0
  243. package/dist/drizzle/session-target.mjs +46 -0
  244. package/dist/drizzle/session-target.mjs.map +1 -0
  245. package/dist/drizzle/sqlite-emails.mjs +45 -0
  246. package/dist/drizzle/sqlite-emails.mjs.map +1 -0
  247. package/dist/drizzle/sqlite-identity.mjs +90 -0
  248. package/dist/drizzle/sqlite-identity.mjs.map +1 -0
  249. package/dist/drizzle/sqlite-password-prepared.mjs +21 -0
  250. package/dist/drizzle/sqlite-password-prepared.mjs.map +1 -0
  251. package/dist/drizzle/sqlite-passwords.mjs +49 -0
  252. package/dist/drizzle/sqlite-passwords.mjs.map +1 -0
  253. package/dist/drizzle/sqlite-proofs.mjs +29 -0
  254. package/dist/drizzle/sqlite-proofs.mjs.map +1 -0
  255. package/dist/drizzle/sqlite-sessions.mjs +74 -0
  256. package/dist/drizzle/sqlite-sessions.mjs.map +1 -0
  257. package/dist/drizzle/sqlite.d.mts +77 -0
  258. package/dist/drizzle/sqlite.mjs +217 -0
  259. package/dist/drizzle/sqlite.mjs.map +1 -0
  260. package/dist/drizzle/standalone-guard.mjs +17 -0
  261. package/dist/drizzle/standalone-guard.mjs.map +1 -0
  262. package/dist/drizzle/step-up-model.d.mts +16 -0
  263. package/dist/drizzle/step-up-model.mjs +2 -0
  264. package/dist/drizzle/table-model.d.mts +11 -0
  265. package/dist/drizzle/totp-model.d.mts +82 -0
  266. package/dist/drizzle/totp-model.mjs +13 -0
  267. package/dist/drizzle/totp-model.mjs.map +1 -0
  268. package/dist/drizzle/totp-state.d.mts +37 -0
  269. package/dist/drizzle/totp-state.mjs +287 -0
  270. package/dist/drizzle/totp-state.mjs.map +1 -0
  271. package/dist/drizzle/totp-target.d.mts +14 -0
  272. package/dist/drizzle/totp-target.mjs +81 -0
  273. package/dist/drizzle/totp-target.mjs.map +1 -0
  274. package/dist/drizzle/transaction-execution.d.mts +2 -0
  275. package/dist/drizzle/transaction-execution.mjs +11 -0
  276. package/dist/drizzle/transaction-execution.mjs.map +1 -0
  277. package/dist/drizzle/transaction-mysql.mjs +47 -0
  278. package/dist/drizzle/transaction-mysql.mjs.map +1 -0
  279. package/dist/drizzle/transaction-owner.d.mts +2 -0
  280. package/dist/drizzle/transaction-owner.mjs +8 -0
  281. package/dist/drizzle/transaction-owner.mjs.map +1 -0
  282. package/dist/index.d.mts +27 -0
  283. package/dist/index.mjs +27 -0
  284. package/dist/internal/drizzle-migrations.mjs +19 -0
  285. package/dist/internal/drizzle-migrations.mjs.map +1 -0
  286. package/dist/internal/drizzle-postgres.mjs +37 -0
  287. package/dist/internal/drizzle-postgres.mjs.map +1 -0
  288. package/dist/internal/drizzle-sqlite.mjs +35 -0
  289. package/dist/internal/drizzle-sqlite.mjs.map +1 -0
  290. package/package.json +1 -0
  291. package/src/D1.ts +136 -0
  292. package/src/Libsql.ts +257 -0
  293. package/src/Mysql2.ts +184 -0
  294. package/src/Pglite.ts +174 -0
  295. package/src/Postgres.ts +174 -0
  296. package/src/SqliteBun.ts +258 -0
  297. package/src/SqliteDo.ts +473 -0
  298. package/src/SqliteNode.ts +259 -0
  299. package/src/SqliteWasm.ts +263 -0
  300. package/src/drizzle/D1BatchStatements.ts +10 -0
  301. package/src/drizzle/SuppliedService.ts +10 -0
  302. package/src/drizzle/d1-emails.ts +1829 -0
  303. package/src/drizzle/d1-generated-statement.ts +129 -0
  304. package/src/drizzle/d1-identity.ts +375 -0
  305. package/src/drizzle/d1-oauth.ts +340 -0
  306. package/src/drizzle/d1-passkey.ts +373 -0
  307. package/src/drizzle/d1-password-prepared.ts +1270 -0
  308. package/src/drizzle/d1-passwords.ts +2656 -0
  309. package/src/drizzle/d1-phone.ts +96 -0
  310. package/src/drizzle/d1-planning.ts +104 -0
  311. package/src/drizzle/d1-proofs.ts +2305 -0
  312. package/src/drizzle/d1-sessions.ts +2857 -0
  313. package/src/drizzle/d1-totp.ts +78 -0
  314. package/src/drizzle/email-model.ts +202 -0
  315. package/src/drizzle/email-registration.ts +698 -0
  316. package/src/drizzle/email-sql.ts +25 -0
  317. package/src/drizzle/email-target.ts +243 -0
  318. package/src/drizzle/model.ts +459 -0
  319. package/src/drizzle/mysql-emails.ts +321 -0
  320. package/src/drizzle/mysql-identity.ts +324 -0
  321. package/src/drizzle/mysql-password-prepared.ts +204 -0
  322. package/src/drizzle/mysql-passwords.ts +339 -0
  323. package/src/drizzle/mysql-proofs.ts +181 -0
  324. package/src/drizzle/mysql-sessions.ts +741 -0
  325. package/src/drizzle/mysql.ts +687 -0
  326. package/src/drizzle/oauth-accounts.ts +804 -0
  327. package/src/drizzle/oauth-connected-access.ts +354 -0
  328. package/src/drizzle/oauth-connected-collection.ts +324 -0
  329. package/src/drizzle/oauth-connected-custody.ts +277 -0
  330. package/src/drizzle/oauth-connected-drivers.ts +465 -0
  331. package/src/drizzle/oauth-connected-flow.ts +441 -0
  332. package/src/drizzle/oauth-connected-input.ts +127 -0
  333. package/src/drizzle/oauth-connected-maintenance.ts +345 -0
  334. package/src/drizzle/oauth-connected-management.ts +365 -0
  335. package/src/drizzle/oauth-connected-model.ts +347 -0
  336. package/src/drizzle/oauth-connected-reference.ts +112 -0
  337. package/src/drizzle/oauth-connected-settlement.ts +226 -0
  338. package/src/drizzle/oauth-connected-state.ts +845 -0
  339. package/src/drizzle/oauth-connected-target.ts +264 -0
  340. package/src/drizzle/oauth-drivers.ts +569 -0
  341. package/src/drizzle/oauth-flow.ts +462 -0
  342. package/src/drizzle/oauth-input.ts +201 -0
  343. package/src/drizzle/oauth-model.ts +617 -0
  344. package/src/drizzle/oauth-mysql.ts +10 -0
  345. package/src/drizzle/oauth-owner.ts +29 -0
  346. package/src/drizzle/oauth-registration.ts +640 -0
  347. package/src/drizzle/oauth-state.ts +215 -0
  348. package/src/drizzle/oauth-target.ts +750 -0
  349. package/src/drizzle/passkey-drivers.ts +385 -0
  350. package/src/drizzle/passkey-kernel.ts +4 -0
  351. package/src/drizzle/passkey-model.ts +153 -0
  352. package/src/drizzle/passkey-registration-ceremony-model.ts +32 -0
  353. package/src/drizzle/passkey-state.ts +3 -0
  354. package/src/drizzle/passkey-target.ts +23 -0
  355. package/src/drizzle/passkey-write-drivers.ts +395 -0
  356. package/src/drizzle/passkey-write-model.ts +103 -0
  357. package/src/drizzle/passkey-write-target.ts +9 -0
  358. package/src/drizzle/password-model.ts +169 -0
  359. package/src/drizzle/password-prepared-model.ts +259 -0
  360. package/src/drizzle/password-prepared-sql.ts +1191 -0
  361. package/src/drizzle/password-prepared-state.ts +231 -0
  362. package/src/drizzle/password-prepared-target.ts +160 -0
  363. package/src/drizzle/password-registration.ts +363 -0
  364. package/src/drizzle/password-sql.ts +13 -0
  365. package/src/drizzle/password-target.ts +224 -0
  366. package/src/drizzle/pg-emails.ts +321 -0
  367. package/src/drizzle/pg-password-prepared.ts +205 -0
  368. package/src/drizzle/pg-passwords.ts +338 -0
  369. package/src/drizzle/pg-proofs.ts +191 -0
  370. package/src/drizzle/pg-sessions.ts +750 -0
  371. package/src/drizzle/pg.ts +984 -0
  372. package/src/drizzle/phone-model.ts +190 -0
  373. package/src/drizzle/phone-state.ts +21 -0
  374. package/src/drizzle/phone-target.ts +472 -0
  375. package/src/drizzle/proof-model.ts +139 -0
  376. package/src/drizzle/proof-sql.ts +10 -0
  377. package/src/drizzle/proof-target.ts +122 -0
  378. package/src/drizzle/query-operations.ts +43 -0
  379. package/src/drizzle/session-model.ts +215 -0
  380. package/src/drizzle/session-sql.ts +14 -0
  381. package/src/drizzle/session-target.ts +338 -0
  382. package/src/drizzle/sqlite-emails.ts +366 -0
  383. package/src/drizzle/sqlite-identity.ts +344 -0
  384. package/src/drizzle/sqlite-password-prepared.ts +260 -0
  385. package/src/drizzle/sqlite-passwords.ts +497 -0
  386. package/src/drizzle/sqlite-proofs.ts +202 -0
  387. package/src/drizzle/sqlite-sessions.ts +971 -0
  388. package/src/drizzle/sqlite.ts +705 -0
  389. package/src/drizzle/standalone-guard.ts +32 -0
  390. package/src/drizzle/step-up-model.ts +73 -0
  391. package/src/drizzle/table-model.ts +9 -0
  392. package/src/drizzle/totp-model.ts +92 -0
  393. package/src/drizzle/totp-state.ts +525 -0
  394. package/src/drizzle/totp-target.ts +308 -0
  395. package/src/drizzle/transaction-execution.ts +13 -0
  396. package/src/drizzle/transaction-mysql.ts +106 -0
  397. package/src/drizzle/transaction-owner.ts +11 -0
  398. package/src/index.ts +378 -0
  399. package/src/internal/drizzle-migrations.ts +29 -0
  400. package/src/internal/drizzle-postgres.ts +83 -0
  401. package/src/internal/drizzle-sqlite.ts +81 -0
@@ -0,0 +1,829 @@
1
+ import { requiredProofConstraints } from "./proof-model.mjs";
2
+ import { PersistenceMappingError, column, isMappedConstraintConflict, updateValues } from "./model.mjs";
3
+ import { balancedD1And } from "./d1-generated-statement.mjs";
4
+ import { D1BatchStatements } from "./D1BatchStatements.mjs";
5
+ import { CurrentD1PlanningDatabase, makeD1Owner } from "./d1-planning.mjs";
6
+ import { and, count, eq, gte, inArray, isNull, lte, notExists, or, sql } from "drizzle-orm";
7
+ import { Cause, Context, Effect, Schema } from "effect";
8
+ import { CurrentCommitJournal, HookConfigurationError, LifecycleHooks, coordinateCommit, hasCommitScope } from "@yielded/auth/Hooks";
9
+ import { reportPersistenceFailure } from "@yielded/auth/Persistence";
10
+ import { ProofBinding, ProofPersistence, ProofRequestConflict, ProofUnavailable } from "@yielded/auth/Proofs";
11
+ //#region src/drizzle/d1-proofs.ts
12
+ const unavailable = () => ProofUnavailable.make({});
13
+ const everyFailureMatches = (cause, classify) => classify !== void 0 && cause.reasons.length > 0 && cause.reasons.every((reason) => Cause.isFailReason(reason) && classify(Cause.fail(reason.error)));
14
+ const conflict = () => ProofRequestConflict.make({});
15
+ const validConstraints = (mapping) => Object.entries(requiredProofConstraints).every(([key, value]) => mapping.constraints[key] === value);
16
+ const canonicalBinding = Schema.encodeSync(Schema.fromJsonString(ProofBinding));
17
+ const sameBinding = (left, right) => canonicalBinding(left) === canonicalBinding(right);
18
+ const containsFailure = (failure, predicate) => {
19
+ const seen = /* @__PURE__ */ new Set();
20
+ const pending = [failure];
21
+ for (let inspected = 0; inspected < 32 && pending.length > 0; inspected++) {
22
+ const current = pending.shift();
23
+ if (current === void 0 || current === null || seen.has(current)) continue;
24
+ seen.add(current);
25
+ if (predicate(current)) return true;
26
+ if (Cause.isCause(current)) {
27
+ for (const reason of current.reasons) if (Cause.isFailReason(reason)) pending.push(reason.error);
28
+ else if (Cause.isDieReason(reason)) pending.push(reason.defect);
29
+ continue;
30
+ }
31
+ if (typeof current !== "object") continue;
32
+ const wrapped = current;
33
+ if (wrapped.cause !== void 0) pending.push(wrapped.cause);
34
+ if (wrapped.reason !== void 0) pending.push(wrapped.reason);
35
+ if (wrapped.message !== void 0) pending.push(wrapped.message);
36
+ }
37
+ return false;
38
+ };
39
+ const isGuardFailure = (cause, marker) => {
40
+ const nativeMessage = `bad JSON path: '${`$[${marker.replaceAll("'", "''")}]`}': SQLITE_ERROR`;
41
+ return containsFailure(cause, (value) => value === nativeMessage || value === `D1_ERROR: ${nativeMessage}`);
42
+ };
43
+ const statement = Effect.fn(function* (query) {
44
+ const database = yield* CurrentD1PlanningDatabase;
45
+ const rendered = query.toSQL();
46
+ return database.$client.unsafe(rendered.sql, rendered.params);
47
+ });
48
+ const readEngineNowMillis = Effect.fn("Drizzle.readEngineNowMillis")(function* (mapping) {
49
+ return yield* (yield* CurrentD1PlanningDatabase).select({ value: mapping.d1.engineNowMillis.as("engine_now_millis") }).from(sql`(select 1)`).pipe(Effect.flatMap((rows) => {
50
+ const value = Number(rows[0]?.value);
51
+ return Number.isFinite(value) ? Effect.succeed(value) : Effect.fail(unavailable());
52
+ }));
53
+ });
54
+ const driverValues = (values, entries) => ({
55
+ ...values,
56
+ ...Object.fromEntries(entries)
57
+ });
58
+ const assertion = Effect.fn(function* (condition, marker) {
59
+ const database = yield* CurrentD1PlanningDatabase;
60
+ return yield* statement(database.select({ ok: sql`case when ${condition} then 1 else json_extract('[]', ${`$[${marker}]`}) end`.as("ok") }).from(sql`(select 1)`));
61
+ });
62
+ const allocateVersion = (mapping) => mapping.allocateVersion !== void 0 ? mapping.allocateVersion : mapping.allocateVersionSync === void 0 ? Effect.fail(unavailable()) : Effect.try({
63
+ try: mapping.allocateVersionSync,
64
+ catch: (cause) => new PersistenceMappingError({
65
+ operation: "mapping",
66
+ cause
67
+ })
68
+ });
69
+ const requestColumns = (mapping) => ({
70
+ moduleId: column(mapping.request.table, mapping.request.moduleId),
71
+ requestId: column(mapping.request.table, mapping.request.requestId),
72
+ fingerprint: column(mapping.request.table, mapping.request.fingerprint),
73
+ proofId: column(mapping.request.table, mapping.request.proofId),
74
+ retentionUntil: column(mapping.request.table, mapping.request.retentionUntil)
75
+ });
76
+ const seriesColumns = (mapping) => ({
77
+ moduleId: column(mapping.series.table, mapping.series.moduleId),
78
+ purpose: column(mapping.series.table, mapping.series.purpose),
79
+ scopeKey: column(mapping.series.table, mapping.series.scopeKey),
80
+ activeProofId: column(mapping.series.table, mapping.series.activeProofId),
81
+ lastIssueAt: column(mapping.series.table, mapping.series.lastIssueAt),
82
+ version: column(mapping.series.table, mapping.series.version)
83
+ });
84
+ const generationColumns = (mapping) => ({
85
+ moduleId: column(mapping.generation.table, mapping.generation.moduleId),
86
+ purpose: column(mapping.generation.table, mapping.generation.purpose),
87
+ proofId: column(mapping.generation.table, mapping.generation.proofId),
88
+ seriesKey: column(mapping.generation.table, mapping.generation.seriesKey),
89
+ deliveryId: column(mapping.generation.table, mapping.generation.deliveryId),
90
+ verifierKeyId: column(mapping.generation.table, mapping.generation.verifierKeyId),
91
+ verifierDigest: column(mapping.generation.table, mapping.generation.verifierDigest),
92
+ expiresAt: column(mapping.generation.table, mapping.generation.expiresAt),
93
+ version: column(mapping.generation.table, mapping.generation.version),
94
+ state: column(mapping.generation.table, mapping.generation.state),
95
+ sendCount: column(mapping.generation.table, mapping.generation.sendCount),
96
+ deliveryState: column(mapping.generation.table, mapping.generation.deliveryState),
97
+ claimVersion: column(mapping.generation.table, mapping.generation.claimVersion),
98
+ claimDeadline: column(mapping.generation.table, mapping.generation.claimDeadline),
99
+ retryAt: column(mapping.generation.table, mapping.generation.retryAt),
100
+ deliveryRetryMillis: column(mapping.generation.table, mapping.generation.deliveryRetryMillis),
101
+ retentionUntil: column(mapping.generation.table, mapping.generation.retentionUntil)
102
+ });
103
+ const continuationColumns = (mapping) => ({
104
+ moduleId: column(mapping.continuation.table, mapping.continuation.moduleId),
105
+ continuationId: column(mapping.continuation.table, mapping.continuation.continuationId),
106
+ digest: column(mapping.continuation.table, mapping.continuation.digest),
107
+ consumed: column(mapping.continuation.table, mapping.continuation.consumed),
108
+ retentionUntil: column(mapping.continuation.table, mapping.continuation.retentionUntil)
109
+ });
110
+ const scopeColumns = (mapping) => ({
111
+ moduleId: column(mapping.rateScope.table, mapping.rateScope.moduleId),
112
+ purpose: column(mapping.rateScope.table, mapping.rateScope.purpose),
113
+ action: column(mapping.rateScope.table, mapping.rateScope.action),
114
+ scopeKind: column(mapping.rateScope.table, mapping.rateScope.scopeKind),
115
+ scopeKey: column(mapping.rateScope.table, mapping.rateScope.scopeKey)
116
+ });
117
+ const abuseColumns = (mapping) => ({
118
+ moduleId: column(mapping.abuseEvent.table, mapping.abuseEvent.moduleId),
119
+ purpose: column(mapping.abuseEvent.table, mapping.abuseEvent.purpose),
120
+ action: column(mapping.abuseEvent.table, mapping.abuseEvent.action),
121
+ scopeKind: column(mapping.abuseEvent.table, mapping.abuseEvent.scopeKind),
122
+ scopeKey: column(mapping.abuseEvent.table, mapping.abuseEvent.scopeKey),
123
+ commandId: column(mapping.abuseEvent.table, mapping.abuseEvent.commandId),
124
+ occurredAt: column(mapping.abuseEvent.table, mapping.abuseEvent.occurredAt),
125
+ retentionUntil: column(mapping.abuseEvent.table, mapping.abuseEvent.retentionUntil)
126
+ });
127
+ const failureColumns = (mapping) => ({
128
+ moduleId: column(mapping.failureEvent.table, mapping.failureEvent.moduleId),
129
+ purpose: column(mapping.failureEvent.table, mapping.failureEvent.purpose),
130
+ seriesKey: column(mapping.failureEvent.table, mapping.failureEvent.seriesKey),
131
+ commandId: column(mapping.failureEvent.table, mapping.failureEvent.commandId),
132
+ occurredAt: column(mapping.failureEvent.table, mapping.failureEvent.occurredAt),
133
+ retentionUntil: column(mapping.failureEvent.table, mapping.failureEvent.retentionUntil)
134
+ });
135
+ const commandColumns = (mapping) => ({
136
+ moduleId: column(mapping.command.table, mapping.command.moduleId),
137
+ commandId: column(mapping.command.table, mapping.command.commandId),
138
+ decision: column(mapping.command.table, mapping.command.decision),
139
+ retentionUntil: column(mapping.command.table, mapping.command.retentionUntil)
140
+ });
141
+ const scopeEntries = (keys, binding, action, policy) => {
142
+ const suffix = action === "issue" ? "Issues" : "Attempts";
143
+ const simple = action === "issue" ? "issues" : "attempts";
144
+ const entries = [{
145
+ kind: "action",
146
+ key: "*",
147
+ budget: policy.abuse[`action${suffix}`]
148
+ }, {
149
+ kind: "identifier",
150
+ key: keys.identifier,
151
+ budget: policy.abuse[simple]
152
+ }];
153
+ if (binding._tag !== "Identifier") entries.push({
154
+ kind: "subject",
155
+ key: keys.subject,
156
+ budget: policy.abuse[`subject${suffix}`]
157
+ });
158
+ return entries;
159
+ };
160
+ const scopeCondition = (mapping, moduleId, purpose, action, entry) => {
161
+ const c = abuseColumns(mapping);
162
+ return sql`(select count(*) from ${mapping.abuseEvent.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.purpose} = ${sql.param(purpose, c.purpose)} and ${c.action} = ${sql.param(action, c.action)} and ${c.scopeKind} = ${sql.param(entry.kind, c.scopeKind)} and ${c.scopeKey} = ${sql.param(entry.key, c.scopeKey)} and ${c.occurredAt} >= ${mapping.d1.engineInstantMinus(entry.budget.windowMillis)}) < ${entry.budget.limit}`;
163
+ };
164
+ const failureCondition = (mapping, moduleId, purpose, seriesKey, policy) => {
165
+ const c = failureColumns(mapping);
166
+ return sql`(select count(*) from ${mapping.failureEvent.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.purpose} = ${sql.param(purpose, c.purpose)} and ${c.seriesKey} = ${sql.param(seriesKey, c.seriesKey)} and ${c.occurredAt} >= ${mapping.d1.engineInstantMinus(policy.abuse.attempts.windowMillis)}) < ${policy.maximumFailedAttempts}`;
167
+ };
168
+ const readScopeAdmission = Effect.fn("DrizzleD1Proof.readScopeAdmission")(function* (mapping, moduleId, purpose, action, entries, now) {
169
+ const database = yield* CurrentD1PlanningDatabase;
170
+ const c = abuseColumns(mapping);
171
+ const admitted = [];
172
+ for (const entry of entries) {
173
+ const rows = yield* database.select({ total: count() }).from(mapping.abuseEvent.table).where(and(eq(c.moduleId, moduleId), eq(c.purpose, purpose), eq(c.action, action), eq(c.scopeKind, entry.kind), eq(c.scopeKey, entry.key), gte(c.occurredAt, mapping.encodeInstant(now - entry.budget.windowMillis))));
174
+ if (Number(rows[0]?.total ?? 0) < entry.budget.limit) admitted.push(entry);
175
+ }
176
+ return admitted;
177
+ });
178
+ const authority = Effect.fn("DrizzleD1Proof.authority")(function* (mapping, moduleId, purpose, binding) {
179
+ const database = yield* CurrentD1PlanningDatabase;
180
+ let nativeSubjectId;
181
+ let subjectCurrent = true;
182
+ const parts = [];
183
+ if (binding._tag !== "Identifier") {
184
+ if (mapping.authority.subject === void 0 || mapping.authority.credential === void 0 || mapping.authority.subjectId === void 0) return yield* unavailable();
185
+ nativeSubjectId = yield* mapping.authority.subjectId.toNative(binding.revision.subjectId);
186
+ const subject = mapping.authority.subject;
187
+ const id = column(subject.table, subject.id);
188
+ const status = column(subject.table, subject.status);
189
+ const revision = column(subject.table, subject.securityRevision);
190
+ const subjectRow = (yield* database.select().from(subject.table).where(eq(id, nativeSubjectId)).limit(1))[0];
191
+ subjectCurrent = subjectRow !== void 0 && subject.isActiveStatus(subjectRow[subject.status]) && subjectRow[subject.securityRevision] === binding.revision.securityRevision;
192
+ parts.push(sql`exists(select 1 from ${subject.table} where ${id} = ${sql.param(nativeSubjectId, id)} and ${status} = ${sql.param(subject.d1ActiveStatusValue, status)} and ${revision} = ${sql.param(binding.revision.securityRevision, revision)})`);
193
+ }
194
+ const identifier = mapping.authority.identifier;
195
+ const namespace = column(identifier.table, identifier.namespace);
196
+ const value = column(identifier.table, identifier.value);
197
+ const identifierRows = yield* database.select().from(identifier.table).where(and(eq(namespace, binding.identifier.namespace), eq(value, binding.identifier.value)));
198
+ const input = {
199
+ moduleId,
200
+ purpose,
201
+ binding,
202
+ ...nativeSubjectId === void 0 ? {} : { nativeSubjectId }
203
+ };
204
+ const identifierCurrent = identifier.isCurrent(input, identifierRows);
205
+ parts.push(identifier.d1CurrentCondition(input));
206
+ let credentialsCurrent = true;
207
+ if (binding._tag !== "Identifier") {
208
+ const credential = mapping.authority.credential;
209
+ const owner = column(credential.table, credential.subjectId);
210
+ const id = column(credential.table, credential.credentialId);
211
+ const revision = column(credential.table, credential.revision);
212
+ const status = credential.status === void 0 ? void 0 : column(credential.table, credential.status);
213
+ const expected = [...binding.revision.credentials].sort((a, b) => a.credentialId.localeCompare(b.credentialId));
214
+ const actual = (expected.length === 0 ? [] : yield* database.select().from(credential.table).where(and(eq(owner, nativeSubjectId), inArray(id, expected.map((item) => item.credentialId))))).map((row) => ({
215
+ id: row[credential.credentialId],
216
+ revision: row[credential.revision],
217
+ active: credential.status === void 0 || credential.isActiveStatus?.(row[credential.status]) === true
218
+ })).sort((a, b) => String(a.id).localeCompare(String(b.id)));
219
+ credentialsCurrent = actual.length === expected.length && actual.every((row, index) => row.active && row.id === expected[index]?.credentialId && row.revision === expected[index]?.revision);
220
+ for (const expectedCredential of expected) parts.push(sql`exists(select 1 from ${credential.table} where ${owner} = ${sql.param(nativeSubjectId, owner)} and ${id} = ${sql.param(expectedCredential.credentialId, id)} and ${revision} = ${sql.param(expectedCredential.revision, revision)}${status === void 0 ? sql`` : sql` and ${status} = ${sql.param(credential.d1ActiveStatusValue, status)}`})`);
221
+ }
222
+ return {
223
+ current: subjectCurrent && identifierCurrent && credentialsCurrent,
224
+ condition: balancedD1And(...parts) ?? sql`1 = 1`
225
+ };
226
+ });
227
+ const anchorStatements = Effect.fn(function* (mapping, moduleId, purpose, action, entries, seriesKey, seriesVersion, includeSeries) {
228
+ const database = yield* CurrentD1PlanningDatabase;
229
+ return [...yield* Effect.forEach(entries, Effect.fn(function* (entry) {
230
+ return yield* statement(database.insert(mapping.rateScope.table).values(mapping.rateScope.encodeInsert({
231
+ moduleId,
232
+ purpose,
233
+ action,
234
+ scopeKind: entry.kind,
235
+ scopeKey: entry.key
236
+ })).onConflictDoNothing());
237
+ })), ...includeSeries ? [yield* statement(database.insert(mapping.series.table).values(mapping.series.encodeInsert({
238
+ moduleId,
239
+ purpose,
240
+ scopeKey: seriesKey,
241
+ version: seriesVersion
242
+ })).onConflictDoNothing())] : []];
243
+ });
244
+ const insertScopeStatements = Effect.fn(function* (mapping, moduleId, purpose, action, commandId, entries, now, retentionUntil, marker) {
245
+ const database = yield* CurrentD1PlanningDatabase;
246
+ return (yield* Effect.forEach(entries, Effect.fn(function* (entry) {
247
+ return [yield* assertion(scopeCondition(mapping, moduleId, purpose, action, entry), marker), yield* statement(database.insert(mapping.abuseEvent.table).values(driverValues(mapping.abuseEvent.encodeInsert({
248
+ moduleId,
249
+ purpose,
250
+ action,
251
+ scopeKind: entry.kind,
252
+ scopeKey: entry.key,
253
+ commandId,
254
+ occurredAtMillis: now,
255
+ retentionUntilMillis: retentionUntil
256
+ }), [[mapping.abuseEvent.occurredAt, mapping.d1.engineNow], [mapping.abuseEvent.retentionUntil, mapping.d1.engineInstantPlus(retentionUntil - now)]])))];
257
+ }))).flat();
258
+ });
259
+ const readSeries = Effect.fn("Drizzle.readSeries")(function* (mapping, moduleId, purpose, key) {
260
+ const database = yield* CurrentD1PlanningDatabase;
261
+ const c = seriesColumns(mapping);
262
+ return yield* database.select().from(mapping.series.table).where(and(eq(c.moduleId, moduleId), eq(c.purpose, purpose), eq(c.scopeKey, key))).limit(1);
263
+ });
264
+ const readGeneration = Effect.fn("Drizzle.readGeneration")(function* (mapping, moduleId, proofId) {
265
+ const database = yield* CurrentD1PlanningDatabase;
266
+ const c = generationColumns(mapping);
267
+ return yield* database.select().from(mapping.generation.table).where(and(eq(c.moduleId, moduleId), eq(c.proofId, proofId))).limit(1);
268
+ });
269
+ const commandInsert = Effect.fn(function* (mapping, moduleId, commandId, kind, decision, retentionUntil, nativeRetention) {
270
+ const database = yield* CurrentD1PlanningDatabase;
271
+ return yield* statement(database.insert(mapping.command.table).values(driverValues(mapping.command.encodeInsert({
272
+ moduleId,
273
+ commandId,
274
+ kind,
275
+ decision,
276
+ retentionUntilMillis: retentionUntil
277
+ }), nativeRetention === void 0 ? [] : [[mapping.command.retentionUntil, nativeRetention]])));
278
+ });
279
+ const issuePlan = Effect.fn("Drizzle.issuePlan")(function* (mapping, input, prepare) {
280
+ const database = yield* CurrentD1PlanningDatabase;
281
+ const journal = yield* CurrentCommitJournal;
282
+ const keys = mapping.scopeKeys({
283
+ moduleId: input.record.moduleId,
284
+ purpose: input.record.purpose,
285
+ binding: input.record.binding
286
+ });
287
+ const current = yield* authority(mapping, input.record.moduleId, input.record.purpose, input.record.binding);
288
+ const now = yield* readEngineNowMillis(mapping);
289
+ const retentionUntil = now + input.policy.requestRetentionMillis;
290
+ const rc = requestColumns(mapping);
291
+ const existingRequest = (yield* database.select().from(mapping.request.table).where(and(eq(rc.moduleId, input.record.moduleId), eq(rc.requestId, input.record.requestId))).limit(1))[0];
292
+ if (existingRequest !== void 0) {
293
+ if ((yield* mapping.decodeInstant(existingRequest[mapping.request.retentionUntil])) > now) {
294
+ if (existingRequest[mapping.request.fingerprint] !== input.record.fingerprint) return yield* conflict();
295
+ return {
296
+ receipt: prepare({
297
+ _tag: "Existing",
298
+ receipt: yield* mapping.request.decodeReceipt(existingRequest)
299
+ }, journal),
300
+ statements: []
301
+ };
302
+ }
303
+ }
304
+ const scopes = scopeEntries(keys, input.record.binding, "issue", input.policy);
305
+ const initiallyAdmitted = yield* readScopeAdmission(mapping, input.record.moduleId, input.record.purpose, "issue", scopes, now);
306
+ const actionOpen = initiallyAdmitted.some((entry) => entry.kind === "action");
307
+ const admitted = actionOpen ? initiallyAdmitted : [];
308
+ const existingSeries = actionOpen ? (yield* readSeries(mapping, input.record.moduleId, input.record.purpose, keys.series))[0] : void 0;
309
+ const seriesVersion = yield* allocateVersion(mapping);
310
+ const active = existingSeries?.[mapping.series.activeProofId];
311
+ const lastIssue = existingSeries?.[mapping.series.lastIssueAt] === null || existingSeries?.[mapping.series.lastIssueAt] === void 0 ? void 0 : yield* mapping.decodeInstant(existingSeries[mapping.series.lastIssueAt]);
312
+ const allowed = current.current && input.eligible && admitted.length === scopes.length && input.record.issuedAtMillis <= now && input.record.expiresAtMillis > now && (input.supersedes === void 0 || input.supersedes === active) && (lastIssue === void 0 || now - lastIssue >= input.policy.abuse.resendCooldownMillis);
313
+ const receipt = {
314
+ requestId: input.record.requestId,
315
+ reference: {
316
+ proofId: input.record.proofId,
317
+ purpose: input.record.purpose,
318
+ keyId: input.record.verifier.keyId
319
+ }
320
+ };
321
+ const prepared = prepare(allowed ? {
322
+ _tag: "Issued",
323
+ record: input.record
324
+ } : {
325
+ _tag: "Suppressed",
326
+ receipt
327
+ }, journal);
328
+ const statements = [];
329
+ const marker = `effect-auth-proof-guard:issue:${input.record.requestId}`;
330
+ if (existingRequest !== void 0) statements.push(yield* statement(database.delete(mapping.request.table).where(and(eq(rc.moduleId, input.record.moduleId), eq(rc.requestId, input.record.requestId), lte(rc.retentionUntil, mapping.d1.engineNow)))));
331
+ statements.push(yield* statement(database.insert(mapping.request.table).values(driverValues(mapping.request.encodeInsert({
332
+ record: input.record,
333
+ createdAtMillis: now,
334
+ retentionUntilMillis: retentionUntil
335
+ }), [[mapping.request.createdAt, mapping.d1.engineNow], [mapping.request.retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)]]))), ...yield* anchorStatements(mapping, input.record.moduleId, input.record.purpose, "issue", actionOpen ? scopes : scopes.slice(0, 1), keys.series, seriesVersion, actionOpen), ...yield* insertScopeStatements(mapping, input.record.moduleId, input.record.purpose, "issue", input.record.requestId, admitted, now, retentionUntil, marker));
336
+ if (allowed) {
337
+ const sc = seriesColumns(mapping);
338
+ const seriesCondition = and(eq(sc.moduleId, input.record.moduleId), eq(sc.purpose, input.record.purpose), eq(sc.scopeKey, keys.series), active === null || active === void 0 ? or(eq(sc.activeProofId, null), sql`${sc.activeProofId} is null`) : eq(sc.activeProofId, active), lastIssue === void 0 ? sql`1 = 1` : lte(sc.lastIssueAt, mapping.d1.engineInstantMinus(input.policy.abuse.resendCooldownMillis)));
339
+ statements.push(yield* assertion(and(current.condition, sql`${mapping.d1.engineNowMillis} >= ${input.record.issuedAtMillis}`, sql`${mapping.d1.engineNow} < ${sql.param(mapping.encodeInstant(input.record.expiresAtMillis), generationColumns(mapping).expiresAt)}`, sql`exists(select 1 from ${mapping.series.table} where ${seriesCondition})`), marker));
340
+ if (active !== null && active !== void 0) statements.push(yield* statement(database.update(mapping.generation.table).set(updateValues([[mapping.generation.state, "superseded"]])).where(and(eq(generationColumns(mapping).moduleId, input.record.moduleId), eq(generationColumns(mapping).proofId, active), eq(generationColumns(mapping).state, "active")))));
341
+ statements.push(yield* statement(database.insert(mapping.generation.table).values(driverValues(mapping.generation.encodeInsert({
342
+ record: input.record,
343
+ seriesKey: keys.series,
344
+ retentionUntilMillis: retentionUntil,
345
+ state: "active",
346
+ deliveryState: "new",
347
+ policy: input.policy
348
+ }), [[mapping.generation.retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)]]))), yield* statement(database.update(mapping.series.table).set(updateValues([
349
+ [mapping.series.activeProofId, input.record.proofId],
350
+ [mapping.series.lastIssueAt, mapping.d1.engineNow],
351
+ [mapping.series.version, seriesVersion]
352
+ ])).where(and(eq(sc.moduleId, input.record.moduleId), eq(sc.purpose, input.record.purpose), eq(sc.scopeKey, keys.series)))));
353
+ }
354
+ return {
355
+ receipt: prepared,
356
+ statements,
357
+ retryable: (cause) => isMappedConstraintConflict(mapping.isRequestConflict, cause) || isMappedConstraintConflict(mapping.isSeriesConflict, cause) || isGuardFailure(cause, marker)
358
+ };
359
+ });
360
+ const attemptPlan = Effect.fn("Drizzle.attemptPlan")(function* (mapping, input, prepare) {
361
+ const database = yield* CurrentD1PlanningDatabase;
362
+ const journal = yield* CurrentCommitJournal;
363
+ const keys = mapping.scopeKeys({
364
+ moduleId: input.moduleId,
365
+ purpose: input.purpose,
366
+ binding: input.binding
367
+ });
368
+ const current = yield* authority(mapping, input.moduleId, input.purpose, input.binding);
369
+ const command = commandColumns(mapping);
370
+ const existingCommand = (yield* database.select().from(mapping.command.table).where(and(eq(command.moduleId, input.moduleId), eq(command.commandId, input.continuationId))).limit(1))[0];
371
+ if (existingCommand !== void 0) {
372
+ if (existingCommand[mapping.command.decision] === "rejected") return {
373
+ receipt: prepare({ _tag: "Rejected" }, journal),
374
+ statements: []
375
+ };
376
+ return yield* unavailable();
377
+ }
378
+ const now = yield* readEngineNowMillis(mapping);
379
+ const scopes = scopeEntries(keys, input.binding, "attempt", input.policy);
380
+ const initiallyAdmitted = yield* readScopeAdmission(mapping, input.moduleId, input.purpose, "attempt", scopes, now);
381
+ const actionOpen = initiallyAdmitted.some((entry) => entry.kind === "action");
382
+ const admitted = actionOpen ? initiallyAdmitted : [];
383
+ const series = actionOpen ? (yield* readSeries(mapping, input.moduleId, input.purpose, keys.series))[0] : void 0;
384
+ const generation = (yield* readGeneration(mapping, input.moduleId, input.proofId))[0];
385
+ const fc = failureColumns(mapping);
386
+ const failureRows = yield* database.select({ total: count() }).from(mapping.failureEvent.table).where(and(eq(fc.moduleId, input.moduleId), eq(fc.purpose, input.purpose), eq(fc.seriesKey, keys.series), gte(fc.occurredAt, mapping.encodeInstant(now - input.policy.abuse.attempts.windowMillis))));
387
+ const failures = Number(failureRows[0]?.total ?? 0);
388
+ const storedBinding = generation === void 0 ? void 0 : yield* mapping.generation.decodeBinding(generation);
389
+ const expires = generation === void 0 ? void 0 : yield* mapping.decodeInstant(generation[mapping.generation.expiresAt]);
390
+ const currentGeneration = generation !== void 0 && generation[mapping.generation.purpose] === input.purpose && generation[mapping.generation.state] === "active" && series?.[mapping.series.activeProofId] === input.proofId && storedBinding !== void 0 && sameBinding(storedBinding, input.binding) && expires !== void 0 && expires > now;
391
+ const candidateMatches = generation !== void 0 && input.candidate !== void 0 && generation[mapping.generation.verifierKeyId] === input.candidate.keyId && generation[mapping.generation.verifierDigest] === input.candidate.digest;
392
+ const accepted = current.current && currentGeneration && candidateMatches && admitted.length === scopes.length && failures < input.policy.maximumFailedAttempts;
393
+ const retentionUntil = now + input.policy.requestRetentionMillis;
394
+ const seriesVersion = yield* allocateVersion(mapping);
395
+ const statements = [...yield* anchorStatements(mapping, input.moduleId, input.purpose, "attempt", actionOpen ? scopes : scopes.slice(0, 1), keys.series, seriesVersion, actionOpen), ...yield* insertScopeStatements(mapping, input.moduleId, input.purpose, "attempt", input.continuationId, admitted, now, retentionUntil, `effect-auth-proof-guard:attempt:${input.continuationId}`)];
396
+ const marker = `effect-auth-proof-guard:attempt:${input.continuationId}`;
397
+ if (!accepted) {
398
+ const prepared = prepare({ _tag: "Rejected" }, journal);
399
+ if (admitted.length === scopes.length && current.current && currentGeneration && !candidateMatches && failures < input.policy.maximumFailedAttempts) {
400
+ const gc = generationColumns(mapping);
401
+ const sc = seriesColumns(mapping);
402
+ statements.push(yield* assertion(and(current.condition, sql`exists(select 1 from ${mapping.series.table} where ${sc.moduleId} = ${sql.param(input.moduleId, sc.moduleId)} and ${sc.purpose} = ${sql.param(input.purpose, sc.purpose)} and ${sc.scopeKey} = ${sql.param(keys.series, sc.scopeKey)} and ${sc.activeProofId} = ${sql.param(input.proofId, sc.activeProofId)})`, sql`exists(select 1 from ${mapping.generation.table} where ${gc.moduleId} = ${sql.param(input.moduleId, gc.moduleId)} and ${gc.proofId} = ${sql.param(input.proofId, gc.proofId)} and ${gc.state} = 'active' and ${gc.expiresAt} > ${mapping.d1.engineNow})`, failureCondition(mapping, input.moduleId, input.purpose, keys.series, input.policy)), marker), yield* statement(database.insert(mapping.failureEvent.table).values(driverValues(mapping.failureEvent.encodeInsert({
403
+ moduleId: input.moduleId,
404
+ purpose: input.purpose,
405
+ seriesKey: keys.series,
406
+ commandId: input.continuationId,
407
+ occurredAtMillis: now,
408
+ retentionUntilMillis: retentionUntil
409
+ }), [[mapping.failureEvent.occurredAt, mapping.d1.engineNow], [mapping.failureEvent.retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)]]))));
410
+ }
411
+ statements.push(yield* commandInsert(mapping, input.moduleId, input.continuationId, "attempt", "rejected", retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)));
412
+ return {
413
+ receipt: prepared,
414
+ statements,
415
+ retryable: (cause) => isMappedConstraintConflict(mapping.isCommandConflict, cause) || isMappedConstraintConflict(mapping.isSeriesConflict, cause) || isGuardFailure(cause, marker)
416
+ };
417
+ }
418
+ const version = yield* allocateVersion(mapping);
419
+ const continuationExpires = Math.min(expires, now + input.policy.continuationLifetimeMillis);
420
+ const continuation = {
421
+ moduleId: input.moduleId,
422
+ purpose: input.purpose,
423
+ continuationId: input.continuationId,
424
+ digest: input.continuationDigest,
425
+ proofId: input.proofId,
426
+ seriesKey: keys.series,
427
+ binding: input.binding,
428
+ expiresAtMillis: continuationExpires,
429
+ version
430
+ };
431
+ const prepared = prepare({
432
+ _tag: "Accepted",
433
+ continuation: {
434
+ continuationId: input.continuationId,
435
+ purpose: input.purpose,
436
+ expiresAtMillis: continuationExpires
437
+ }
438
+ }, journal);
439
+ const gc = generationColumns(mapping);
440
+ const sc = seriesColumns(mapping);
441
+ statements.push(yield* assertion(and(current.condition, failureCondition(mapping, input.moduleId, input.purpose, keys.series, input.policy), sql`exists(select 1 from ${mapping.series.table} where ${sc.moduleId} = ${sql.param(input.moduleId, sc.moduleId)} and ${sc.purpose} = ${sql.param(input.purpose, sc.purpose)} and ${sc.scopeKey} = ${sql.param(keys.series, sc.scopeKey)} and ${sc.activeProofId} = ${sql.param(input.proofId, sc.activeProofId)})`, sql`exists(select 1 from ${mapping.generation.table} where ${gc.moduleId} = ${sql.param(input.moduleId, gc.moduleId)} and ${gc.proofId} = ${sql.param(input.proofId, gc.proofId)} and ${gc.purpose} = ${sql.param(input.purpose, gc.purpose)} and ${gc.state} = 'active' and ${gc.verifierKeyId} = ${sql.param(input.candidate.keyId, gc.verifierKeyId)} and ${gc.verifierDigest} = ${sql.param(input.candidate.digest, gc.verifierDigest)} and ${gc.expiresAt} > ${mapping.d1.engineNow})`), marker), yield* commandInsert(mapping, input.moduleId, input.continuationId, "attempt", "accepted", retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)), yield* statement(database.update(mapping.generation.table).set(updateValues([[mapping.generation.state, "consumed"]])).where(and(eq(gc.moduleId, input.moduleId), eq(gc.proofId, input.proofId), eq(gc.state, "active")))), yield* statement(database.insert(mapping.continuation.table).values(driverValues(mapping.continuation.encodeInsert({
442
+ ...continuation,
443
+ retentionUntilMillis: retentionUntil
444
+ }), [[mapping.continuation.retentionUntil, mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis)]]))));
445
+ return {
446
+ receipt: prepared,
447
+ statements,
448
+ retryable: (cause) => isMappedConstraintConflict(mapping.isCommandConflict, cause) || isMappedConstraintConflict(mapping.isSeriesConflict, cause) || isGuardFailure(cause, marker)
449
+ };
450
+ });
451
+ const inspectD1Completion = Effect.fn("DrizzleD1Proof.inspectCompletion")(function* (mapping, input) {
452
+ const database = yield* CurrentD1PlanningDatabase;
453
+ const keys = mapping.scopeKeys({
454
+ moduleId: input.moduleId,
455
+ purpose: input.purpose,
456
+ binding: input.binding
457
+ });
458
+ const current = yield* authority(mapping, input.moduleId, input.purpose, input.binding);
459
+ const c = continuationColumns(mapping);
460
+ const row = (yield* database.select().from(mapping.continuation.table).where(and(eq(c.moduleId, input.moduleId), eq(c.continuationId, input.continuationId))).limit(1))[0];
461
+ const now = yield* readEngineNowMillis(mapping);
462
+ const record = row === void 0 ? void 0 : yield* mapping.continuation.decode(row);
463
+ const accepted = current.current && record !== void 0 && record.moduleId === input.moduleId && record.continuationId === input.continuationId && record.purpose === input.purpose && record.digest === input.continuationDigest && record.seriesKey === keys.series && sameBinding(record.binding, input.binding) && row[mapping.continuation.consumed] === false && record.expiresAtMillis > now;
464
+ const immutable = [
465
+ mapping.continuation.moduleId,
466
+ mapping.continuation.purpose,
467
+ mapping.continuation.continuationId,
468
+ mapping.continuation.digest,
469
+ mapping.continuation.proofId,
470
+ mapping.continuation.seriesKey,
471
+ mapping.continuation.binding,
472
+ mapping.continuation.expiresAt,
473
+ mapping.continuation.version,
474
+ mapping.continuation.retentionUntil
475
+ ];
476
+ const exact = row === void 0 ? sql`false` : and(...immutable.map((key) => eq(column(mapping.continuation.table, key), row[key])));
477
+ return {
478
+ accepted,
479
+ record,
480
+ row,
481
+ columns: c,
482
+ condition: and(current.condition, sql`exists(select 1 from ${mapping.continuation.table} where ${exact} and ${c.consumed} = ${sql.param(false, c.consumed)} and ${column(mapping.continuation.table, mapping.continuation.expiresAt)} > ${mapping.d1.engineNow})`),
483
+ appliedCondition: row === void 0 ? sql`false` : sql`exists(select 1 from ${mapping.continuation.table} where ${exact} and ${c.consumed} = ${sql.param(true, c.consumed)} and ${column(mapping.continuation.table, mapping.continuation.expiresAt)} > ${mapping.d1.engineNow})`
484
+ };
485
+ });
486
+ /** Read-only preflight plus its exact final-engine-time batch predicate. */
487
+ const checkD1ProofCompletion = Effect.fn("Drizzle.checkD1ProofCompletion")(function* (mapping, input) {
488
+ return yield* inspectD1Completion(mapping, input);
489
+ });
490
+ const completionPlan = Effect.fn("Drizzle.completionPlan")(function* (mapping, input, prepare) {
491
+ const database = yield* CurrentD1PlanningDatabase;
492
+ const journal = yield* CurrentCommitJournal;
493
+ const inspected = yield* inspectD1Completion(mapping, input);
494
+ const { accepted, record, columns: c } = inspected;
495
+ const receipt = prepare(accepted ? "completed" : "rejected", journal);
496
+ if (!accepted) return {
497
+ receipt,
498
+ statements: []
499
+ };
500
+ const postconditions = [yield* assertion(and(inspected.appliedCondition, sql`exists(select 1 from ${mapping.command.table} where ${column(mapping.command.table, mapping.command.moduleId)} = ${sql.param(input.moduleId, column(mapping.command.table, mapping.command.moduleId))} and ${column(mapping.command.table, mapping.command.commandId)} = ${sql.param(input.continuationDigest, column(mapping.command.table, mapping.command.commandId))} and ${column(mapping.command.table, mapping.command.kind)} = ${sql.param("complete", column(mapping.command.table, mapping.command.kind))} and ${column(mapping.command.table, mapping.command.decision)} = ${sql.param("completed", column(mapping.command.table, mapping.command.decision))} and ${column(mapping.command.table, mapping.command.retentionUntil)} = ${sql.param(mapping.encodeInstant(record.expiresAtMillis), column(mapping.command.table, mapping.command.retentionUntil))})`), `effect-auth-proof-guard:complete:${input.continuationId}`)];
501
+ return {
502
+ receipt,
503
+ statements: [
504
+ yield* assertion(inspected.condition, `effect-auth-proof-guard:complete:${input.continuationId}`),
505
+ yield* statement(database.update(mapping.continuation.table).set(updateValues([[mapping.continuation.consumed, true]])).where(and(eq(c.moduleId, input.moduleId), eq(c.continuationId, input.continuationId), eq(c.digest, input.continuationDigest), eq(c.consumed, false)))),
506
+ yield* commandInsert(mapping, input.moduleId, input.continuationDigest, "complete", "completed", record.expiresAtMillis),
507
+ ...postconditions
508
+ ],
509
+ postconditions,
510
+ retryable: (cause) => isMappedConstraintConflict(mapping.isCommandConflict, cause) || isGuardFailure(cause, `effect-auth-proof-guard:complete:${input.continuationId}`)
511
+ };
512
+ });
513
+ const makeProofPlans = (mapping) => {
514
+ const run = (plan) => Effect.gen(function* () {
515
+ if (!validConstraints(mapping)) return yield* unavailable();
516
+ return yield* plan;
517
+ });
518
+ return {
519
+ issue: (input, prepare) => run(Effect.gen(function* () {
520
+ return yield* issuePlan(mapping, input, prepare);
521
+ })),
522
+ attempt: (input, prepare) => run(Effect.gen(function* () {
523
+ return yield* attemptPlan(mapping, input, prepare);
524
+ })),
525
+ complete: (input, prepare) => run(Effect.gen(function* () {
526
+ return yield* completionPlan(mapping, input, prepare);
527
+ })),
528
+ claimDelivery: (input, prepare) => Effect.gen(function* () {
529
+ const database = yield* CurrentD1PlanningDatabase;
530
+ return yield* run(Effect.gen(function* () {
531
+ const journal = yield* CurrentCommitJournal;
532
+ const row = (yield* readGeneration(mapping, input.moduleId, input.proofId))[0];
533
+ const now = yield* readEngineNowMillis(mapping);
534
+ const c = generationColumns(mapping);
535
+ if (row === void 0) return {
536
+ receipt: prepare({ _tag: "Declined" }, journal),
537
+ statements: []
538
+ };
539
+ const expires = yield* mapping.decodeInstant(row[mapping.generation.expiresAt]);
540
+ const claimDeadline = row[mapping.generation.claimDeadline] === null || row[mapping.generation.claimDeadline] === void 0 ? void 0 : yield* mapping.decodeInstant(row[mapping.generation.claimDeadline]);
541
+ const retryAt = row[mapping.generation.retryAt] === null || row[mapping.generation.retryAt] === void 0 ? void 0 : yield* mapping.decodeInstant(row[mapping.generation.retryAt]);
542
+ const state = row[mapping.generation.deliveryState];
543
+ const expiredClaim = state === "claimed" && claimDeadline !== void 0 && claimDeadline <= now;
544
+ const effectiveState = expiredClaim ? "ambiguous" : state;
545
+ if (!(row[mapping.generation.version] === input.version && row[mapping.generation.deliveryId] === input.deliveryId && row[mapping.generation.state] === "active" && expires > now && Number(row[mapping.generation.sendCount]) < input.policy.maximumDeliveryAttempts && (effectiveState === "new" || effectiveState === "ambiguous" && input.allowAmbiguousRetry && (retryAt === void 0 || retryAt <= now)))) {
546
+ const statements = expiredClaim ? [yield* statement(database.update(mapping.generation.table).set(updateValues([[mapping.generation.deliveryState, "ambiguous"]])).where(and(eq(c.moduleId, input.moduleId), eq(c.proofId, input.proofId), eq(c.deliveryState, "claimed"), lte(c.claimDeadline, mapping.d1.engineNow))))] : [];
547
+ return {
548
+ receipt: prepare({ _tag: "Declined" }, journal),
549
+ statements
550
+ };
551
+ }
552
+ const claimVersion = yield* allocateVersion(mapping);
553
+ const decision = {
554
+ _tag: "Claimed",
555
+ claimVersion
556
+ };
557
+ const condition = and(eq(c.moduleId, input.moduleId), eq(c.proofId, input.proofId), eq(c.version, input.version), eq(c.deliveryId, input.deliveryId), eq(c.state, "active"), sql`${c.expiresAt} > ${mapping.d1.engineNow}`, sql`${c.sendCount} < ${input.policy.maximumDeliveryAttempts}`, effectiveState === "new" ? eq(c.deliveryState, "new") : and(eq(c.deliveryState, "ambiguous"), or(sql`${c.retryAt} is null`, lte(c.retryAt, mapping.d1.engineNow))));
558
+ return {
559
+ receipt: prepare(decision, journal),
560
+ statements: [yield* assertion(sql`exists(select 1 from ${mapping.generation.table} where ${condition})`, `effect-auth-proof-guard:claim:${input.proofId}`), yield* statement(database.update(mapping.generation.table).set(updateValues([
561
+ [mapping.generation.sendCount, Number(row[mapping.generation.sendCount]) + 1],
562
+ [mapping.generation.deliveryState, "claimed"],
563
+ [mapping.generation.claimVersion, claimVersion],
564
+ [mapping.generation.claimDeadline, mapping.d1.engineInstantPlus(input.policy.deliveryClaimMillis)],
565
+ [mapping.generation.retryAt, mapping.d1.engineInstantPlus(input.policy.deliveryRetryMillis)]
566
+ ])).where(condition))],
567
+ retryable: (cause) => isGuardFailure(cause, `effect-auth-proof-guard:claim:${input.proofId}`)
568
+ };
569
+ }));
570
+ }),
571
+ settleDelivery: (input, prepare) => Effect.gen(function* () {
572
+ const database = yield* CurrentD1PlanningDatabase;
573
+ return yield* run(Effect.gen(function* () {
574
+ const journal = yield* CurrentCommitJournal;
575
+ const row = (yield* readGeneration(mapping, input.moduleId, input.proofId))[0];
576
+ const receipt = prepare(void 0, journal);
577
+ if (row === void 0 || row[mapping.generation.version] !== input.version || row[mapping.generation.deliveryId] !== input.deliveryId || row[mapping.generation.claimVersion] !== input.claimVersion || row[mapping.generation.deliveryState] !== "claimed") return {
578
+ receipt,
579
+ statements: []
580
+ };
581
+ const c = generationColumns(mapping);
582
+ const outcome = input.outcome;
583
+ const state = outcome._tag === "Accepted" ? "accepted" : outcome._tag === "DefiniteFailure" ? "failed" : "ambiguous";
584
+ const values = [[mapping.generation.deliveryState, state], [mapping.generation.claimDeadline, null]];
585
+ if (outcome._tag === "Ambiguous") values.push([mapping.generation.retryAt, mapping.d1.engineInstantPlus(Number(row[mapping.generation.deliveryRetryMillis]))]);
586
+ if (outcome._tag === "DefiniteFailure") values.push([mapping.generation.state, "cancelled"]);
587
+ const condition = and(eq(c.moduleId, input.moduleId), eq(c.proofId, input.proofId), eq(c.version, input.version), eq(c.deliveryId, input.deliveryId), eq(c.claimVersion, input.claimVersion), eq(c.deliveryState, "claimed"));
588
+ const statements = [yield* statement(database.update(mapping.generation.table).set(updateValues(values)).where(condition))];
589
+ if (outcome._tag === "DefiniteFailure") {
590
+ const sc = seriesColumns(mapping);
591
+ statements.push(yield* statement(database.update(mapping.series.table).set(updateValues([[mapping.series.activeProofId, null]])).where(and(eq(sc.moduleId, input.moduleId), eq(sc.purpose, row[mapping.generation.purpose]), eq(sc.scopeKey, row[mapping.generation.seriesKey]), eq(sc.activeProofId, input.proofId), sql`exists(select 1 from ${mapping.generation.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.proofId} = ${sql.param(input.proofId, c.proofId)} and ${c.version} = ${sql.param(input.version, c.version)} and ${c.deliveryId} = ${sql.param(input.deliveryId, c.deliveryId)} and ${c.claimVersion} = ${sql.param(input.claimVersion, c.claimVersion)} and ${c.deliveryState} = 'failed' and ${c.state} = 'cancelled')`))));
592
+ }
593
+ return {
594
+ receipt,
595
+ statements
596
+ };
597
+ }));
598
+ }),
599
+ cancel: (input, prepare) => Effect.gen(function* () {
600
+ const database = yield* CurrentD1PlanningDatabase;
601
+ return yield* run(Effect.gen(function* () {
602
+ const journal = yield* CurrentCommitJournal;
603
+ const keys = mapping.scopeKeys({
604
+ moduleId: input.moduleId,
605
+ purpose: input.purpose,
606
+ binding: input.binding
607
+ });
608
+ const current = yield* authority(mapping, input.moduleId, input.purpose, input.binding);
609
+ const series = (yield* readSeries(mapping, input.moduleId, input.purpose, keys.series))[0];
610
+ const receipt = prepare(void 0, journal);
611
+ const active = series?.[mapping.series.activeProofId];
612
+ if (!current.current || active === null || active === void 0) return {
613
+ receipt,
614
+ statements: []
615
+ };
616
+ const generation = (yield* readGeneration(mapping, input.moduleId, active))[0];
617
+ const storedBinding = generation === void 0 ? void 0 : yield* mapping.generation.decodeBinding(generation);
618
+ if (storedBinding === void 0 || !sameBinding(storedBinding, input.binding)) return {
619
+ receipt,
620
+ statements: []
621
+ };
622
+ const gc = generationColumns(mapping);
623
+ const sc = seriesColumns(mapping);
624
+ const marker = `effect-auth-proof-guard:cancel:${active}`;
625
+ return {
626
+ receipt,
627
+ statements: [
628
+ yield* assertion(and(current.condition, sql`exists(select 1 from ${mapping.series.table} where ${sc.moduleId} = ${sql.param(input.moduleId, sc.moduleId)} and ${sc.purpose} = ${sql.param(input.purpose, sc.purpose)} and ${sc.scopeKey} = ${sql.param(keys.series, sc.scopeKey)} and ${sc.activeProofId} = ${sql.param(active, sc.activeProofId)})`, sql`exists(select 1 from ${mapping.generation.table} where ${gc.moduleId} = ${sql.param(input.moduleId, gc.moduleId)} and ${gc.proofId} = ${sql.param(active, gc.proofId)} and ${gc.state} = 'active')`), marker),
629
+ yield* statement(database.update(mapping.generation.table).set(updateValues([[mapping.generation.state, "cancelled"]])).where(and(eq(gc.moduleId, input.moduleId), eq(gc.proofId, active), eq(gc.state, "active")))),
630
+ yield* statement(database.update(mapping.series.table).set(updateValues([[mapping.series.activeProofId, null]])).where(and(eq(sc.moduleId, input.moduleId), eq(sc.purpose, input.purpose), eq(sc.scopeKey, keys.series), eq(sc.activeProofId, active))))
631
+ ],
632
+ retryable: (cause) => isGuardFailure(cause, marker)
633
+ };
634
+ }));
635
+ }),
636
+ cleanup: (input, prepare) => Effect.gen(function* () {
637
+ const database = yield* CurrentD1PlanningDatabase;
638
+ return yield* run(Effect.gen(function* () {
639
+ const journal = yield* CurrentCommitJournal;
640
+ const now = yield* readEngineNowMillis(mapping);
641
+ const nativeNow = mapping.encodeInstant(now);
642
+ const gc = generationColumns(mapping);
643
+ const cc = continuationColumns(mapping);
644
+ const rc = requestColumns(mapping);
645
+ const ac = abuseColumns(mapping);
646
+ const fc = failureColumns(mapping);
647
+ const mc = commandColumns(mapping);
648
+ const sc = seriesColumns(mapping);
649
+ const rsc = scopeColumns(mapping);
650
+ let remaining = input.limit;
651
+ let hasMore = false;
652
+ const take = (effect) => effect.pipe(Effect.map((rows) => {
653
+ if (rows.length > remaining) hasMore = true;
654
+ const selected = rows.slice(0, remaining);
655
+ remaining -= selected.length;
656
+ return selected;
657
+ }));
658
+ const continuations = yield* take(database.select({ continuationId: cc.continuationId }).from(mapping.continuation.table).where(and(eq(cc.moduleId, input.moduleId), lte(cc.retentionUntil, nativeNow))).limit(remaining + 1));
659
+ const generations = yield* take(database.select({ proofId: gc.proofId }).from(mapping.generation.table).where(and(eq(gc.moduleId, input.moduleId), lte(gc.retentionUntil, nativeNow))).limit(remaining + 1));
660
+ const requests = yield* take(database.select({ requestId: rc.requestId }).from(mapping.request.table).where(and(eq(rc.moduleId, input.moduleId), lte(rc.retentionUntil, nativeNow))).limit(remaining + 1));
661
+ const abuse = yield* take(database.select({
662
+ action: ac.action,
663
+ scopeKind: ac.scopeKind,
664
+ scopeKey: ac.scopeKey,
665
+ commandId: ac.commandId
666
+ }).from(mapping.abuseEvent.table).where(and(eq(ac.moduleId, input.moduleId), lte(ac.retentionUntil, nativeNow))).limit(remaining + 1));
667
+ const failures = yield* take(database.select({
668
+ seriesKey: fc.seriesKey,
669
+ commandId: fc.commandId
670
+ }).from(mapping.failureEvent.table).where(and(eq(fc.moduleId, input.moduleId), lte(fc.retentionUntil, nativeNow))).limit(remaining + 1));
671
+ const commands = yield* take(database.select({ commandId: mc.commandId }).from(mapping.command.table).where(and(eq(mc.moduleId, input.moduleId), lte(mc.retentionUntil, nativeNow))).limit(remaining + 1));
672
+ const series = yield* take(database.select({
673
+ purpose: sc.purpose,
674
+ scopeKey: sc.scopeKey
675
+ }).from(mapping.series.table).where(and(eq(sc.moduleId, input.moduleId), isNull(sc.activeProofId), notExists(database.select({ one: sql`1` }).from(mapping.generation.table).where(and(eq(gc.moduleId, sc.moduleId), eq(gc.purpose, sc.purpose), eq(gc.seriesKey, sc.scopeKey)))), notExists(database.select({ one: sql`1` }).from(mapping.failureEvent.table).where(and(eq(fc.moduleId, sc.moduleId), eq(fc.purpose, sc.purpose), eq(fc.seriesKey, sc.scopeKey)))))).limit(remaining + 1));
676
+ const rateScopes = yield* take(database.select({
677
+ purpose: rsc.purpose,
678
+ action: rsc.action,
679
+ scopeKind: rsc.scopeKind,
680
+ scopeKey: rsc.scopeKey
681
+ }).from(mapping.rateScope.table).where(and(eq(rsc.moduleId, input.moduleId), notExists(database.select({ one: sql`1` }).from(mapping.abuseEvent.table).where(and(eq(ac.moduleId, rsc.moduleId), eq(ac.purpose, rsc.purpose), eq(ac.action, rsc.action), eq(ac.scopeKind, rsc.scopeKind), eq(ac.scopeKey, rsc.scopeKey)))))).limit(remaining + 1));
682
+ const marker = `effect-auth-proof-guard:cleanup:${input.moduleId}:${now}`;
683
+ const statements = [];
684
+ const guardedDelete = Effect.fn(function* (condition, query) {
685
+ statements.push(yield* assertion(condition, marker), yield* statement(query));
686
+ });
687
+ for (const row of continuations) {
688
+ const condition = and(eq(cc.moduleId, input.moduleId), eq(cc.continuationId, row.continuationId), lte(cc.retentionUntil, mapping.d1.engineNow));
689
+ yield* guardedDelete(sql`exists(select 1 from ${mapping.continuation.table} where ${condition})`, database.delete(mapping.continuation.table).where(condition));
690
+ }
691
+ for (const row of generations) {
692
+ const condition = and(eq(gc.moduleId, input.moduleId), eq(gc.proofId, row.proofId), lte(gc.retentionUntil, mapping.d1.engineNow));
693
+ yield* guardedDelete(sql`exists(select 1 from ${mapping.generation.table} where ${condition})`, database.update(mapping.series.table).set(updateValues([[mapping.series.activeProofId, null]])).where(and(eq(sc.moduleId, input.moduleId), eq(sc.activeProofId, row.proofId))));
694
+ statements.push(yield* statement(database.delete(mapping.generation.table).where(condition)));
695
+ }
696
+ for (const row of requests) {
697
+ const condition = and(eq(rc.moduleId, input.moduleId), eq(rc.requestId, row.requestId), lte(rc.retentionUntil, mapping.d1.engineNow));
698
+ yield* guardedDelete(sql`exists(select 1 from ${mapping.request.table} where ${condition})`, database.delete(mapping.request.table).where(condition));
699
+ }
700
+ for (const row of abuse) {
701
+ const condition = and(eq(ac.moduleId, input.moduleId), eq(ac.action, row.action), eq(ac.scopeKind, row.scopeKind), eq(ac.scopeKey, row.scopeKey), eq(ac.commandId, row.commandId), lte(ac.retentionUntil, mapping.d1.engineNow));
702
+ yield* guardedDelete(sql`exists(select 1 from ${mapping.abuseEvent.table} where ${condition})`, database.delete(mapping.abuseEvent.table).where(condition));
703
+ }
704
+ for (const row of failures) {
705
+ const condition = and(eq(fc.moduleId, input.moduleId), eq(fc.seriesKey, row.seriesKey), eq(fc.commandId, row.commandId), lte(fc.retentionUntil, mapping.d1.engineNow));
706
+ yield* guardedDelete(sql`exists(select 1 from ${mapping.failureEvent.table} where ${condition})`, database.delete(mapping.failureEvent.table).where(condition));
707
+ }
708
+ for (const row of commands) {
709
+ const condition = and(eq(mc.moduleId, input.moduleId), eq(mc.commandId, row.commandId), lte(mc.retentionUntil, mapping.d1.engineNow));
710
+ yield* guardedDelete(sql`exists(select 1 from ${mapping.command.table} where ${condition})`, database.delete(mapping.command.table).where(condition));
711
+ }
712
+ for (const row of series) {
713
+ const condition = and(eq(sc.moduleId, input.moduleId), eq(sc.purpose, row.purpose), eq(sc.scopeKey, row.scopeKey), isNull(sc.activeProofId), notExists(database.select({ one: sql`1` }).from(mapping.generation.table).where(and(eq(gc.moduleId, sc.moduleId), eq(gc.purpose, sc.purpose), eq(gc.seriesKey, sc.scopeKey)))));
714
+ yield* guardedDelete(sql`exists(select 1 from ${mapping.series.table} where ${condition})`, database.delete(mapping.series.table).where(condition));
715
+ }
716
+ for (const row of rateScopes) {
717
+ const condition = and(eq(rsc.moduleId, input.moduleId), eq(rsc.purpose, row.purpose), eq(rsc.action, row.action), eq(rsc.scopeKind, row.scopeKind), eq(rsc.scopeKey, row.scopeKey), notExists(database.select({ one: sql`1` }).from(mapping.abuseEvent.table).where(and(eq(ac.moduleId, rsc.moduleId), eq(ac.purpose, rsc.purpose), eq(ac.action, rsc.action), eq(ac.scopeKind, rsc.scopeKind), eq(ac.scopeKey, rsc.scopeKey)))));
718
+ yield* guardedDelete(sql`exists(select 1 from ${mapping.rateScope.table} where ${condition})`, database.delete(mapping.rateScope.table).where(condition));
719
+ }
720
+ hasMore ||= generations.length > 0 || failures.length > 0 || abuse.length > 0;
721
+ return {
722
+ receipt: prepare({
723
+ removed: input.limit - remaining,
724
+ hasMore
725
+ }, journal),
726
+ statements,
727
+ retryable: (cause) => isGuardFailure(cause, marker)
728
+ };
729
+ }));
730
+ })
731
+ };
732
+ };
733
+ const makeD1ProofPersistenceServices = (database, mapping) => Effect.gen(function* () {
734
+ const hooks = yield* LifecycleHooks;
735
+ const plans = makeProofPlans(mapping);
736
+ const run = (plan) => Effect.gen(function* () {
737
+ if (yield* hasCommitScope) return yield* unavailable();
738
+ return yield* executeStandalone(plan, 2);
739
+ }).pipe(Effect.provideService(CurrentD1PlanningDatabase, database), Effect.provideService(LifecycleHooks, hooks));
740
+ return { proofPersistence: {
741
+ issue: (input, prepare) => run(plans.issue(input, prepare)).pipe(translateIssueFailure),
742
+ attempt: (input, prepare) => run(plans.attempt(input, prepare)).pipe(translateFailure),
743
+ complete: (input, prepare) => run(plans.complete(input, prepare)).pipe(translateFailure),
744
+ claimDelivery: (input, prepare) => run(plans.claimDelivery(input, prepare)).pipe(translateFailure),
745
+ settleDelivery: (input, prepare) => run(plans.settleDelivery(input, prepare)).pipe(translateFailure),
746
+ cancel: (input, prepare) => run(plans.cancel(input, prepare)).pipe(translateFailure),
747
+ cleanup: (input, prepare) => run(plans.cleanup(input, prepare)).pipe(translateFailure)
748
+ } };
749
+ });
750
+ /**
751
+ * Owns one proof transition plus application statements in one D1 batch. It
752
+ * never replays the owner effect. A reserved guard or named race becomes
753
+ * ProofUnavailable so the caller can retry the entire command with fresh secrets.
754
+ */
755
+ function coordinateD1ProofPersistence(acquire, options, body) {
756
+ return Effect.flatMap(acquire, (database) => Effect.gen(function* () {
757
+ const hooks = yield* LifecycleHooks;
758
+ if (yield* hasCommitScope) return yield* unavailable();
759
+ return (yield* coordinateCommit(() => Effect.gen(function* () {
760
+ const statements = [];
761
+ let mutation;
762
+ const nativeCollector = D1BatchStatements.of({ append: (statement) => Effect.sync(() => statements.push(statement)) });
763
+ const owner = yield* makeD1Owner(unavailable()).pipe(Effect.provideService(D1BatchStatements, nativeCollector));
764
+ const plans = makeProofPlans(options.mapping);
765
+ const run = (plan) => coordinateCommit(() => Effect.gen(function* () {
766
+ const journal = yield* CurrentCommitJournal;
767
+ const planned = yield* plan;
768
+ yield* owner.check;
769
+ if (mutation !== void 0) return yield* unavailable();
770
+ const guarded = {
771
+ ...planned,
772
+ journalGuard: journal.prepare(void 0)
773
+ };
774
+ mutation = guarded;
775
+ statements.push(...guarded.statements);
776
+ return guarded.receipt;
777
+ }), { mode: "batch" }).pipe(Effect.map((result) => result.value), Effect.provideService(CurrentD1PlanningDatabase, database), Effect.provideService(LifecycleHooks, hooks));
778
+ const provided = Context.make(ProofPersistence, {
779
+ issue: (input, prepare) => owner.run(run(plans.issue(input, prepare)).pipe(translateIssueFailure)),
780
+ attempt: (input, prepare) => owner.run(run(plans.attempt(input, prepare)).pipe(translateFailure)),
781
+ complete: (input, prepare) => owner.run(run(plans.complete(input, prepare)).pipe(translateFailure)),
782
+ claimDelivery: (input, prepare) => owner.run(run(plans.claimDelivery(input, prepare)).pipe(translateFailure)),
783
+ settleDelivery: (input, prepare) => owner.run(run(plans.settleDelivery(input, prepare)).pipe(translateFailure)),
784
+ cancel: (input, prepare) => owner.run(run(plans.cancel(input, prepare)).pipe(translateFailure)),
785
+ cleanup: (input, prepare) => owner.run(run(plans.cleanup(input, prepare)).pipe(translateFailure))
786
+ }).pipe(Context.add(D1BatchStatements, owner.collector));
787
+ const value = yield* owner.close(Effect.provideContext(body, provided));
788
+ if (mutation?.journalGuard !== void 0) {
789
+ const status = yield* Effect.result(mutation.journalGuard.read);
790
+ if (status._tag === "Success" || status.failure._tag !== "CommitPending") return yield* unavailable();
791
+ }
792
+ yield* database.$client.batch(statements).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (error) => everyFailureMatches(cause, mutation?.retryable) ? unavailable() : error))), translateFailure);
793
+ return value;
794
+ }), { mode: "batch" }).pipe(Effect.provideService(LifecycleHooks, hooks))).value;
795
+ }));
796
+ }
797
+ /** Private compiler seam for a future same-owner D1 password-reset batch. */
798
+ const compileD1ProofCompletionPlan = Effect.fn("Drizzle.compileD1ProofCompletionPlan")(function* (mapping, plan, protectedMutation, project) {
799
+ const planned = yield* completionPlan(mapping, plan.input, (decision, activeJournal) => plan.prepare(decision, activeJournal, project));
800
+ if (planned.statements.length === 0) return planned;
801
+ const [freshGuard, ...completionStatements] = planned.statements;
802
+ const marker = `effect-auth-proof-guard:protected:${plan.input.continuationId}`;
803
+ return {
804
+ receipt: planned.receipt,
805
+ statements: [
806
+ freshGuard,
807
+ ...protectedMutation.statements,
808
+ yield* assertion(protectedMutation.appliedCondition, marker),
809
+ ...completionStatements
810
+ ],
811
+ postconditions: [yield* assertion(protectedMutation.appliedCondition, marker), ...planned.postconditions ?? []]
812
+ };
813
+ });
814
+ const translateFailure = (effect) => reportPersistenceFailure(effect, (error) => Schema.is(ProofUnavailable)(error) || Schema.is(HookConfigurationError)(error)).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => unavailable()))));
815
+ const translateIssueFailure = (effect) => reportPersistenceFailure(effect, (error) => Schema.is(ProofUnavailable)(error) || Schema.is(ProofRequestConflict)(error) || Schema.is(HookConfigurationError)(error)).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (error) => Schema.is(ProofRequestConflict)(error) ? error : unavailable()))));
816
+ const executeStandalone = (plan, retries = 2) => Effect.suspend(() => {
817
+ let retryable;
818
+ return coordinateCommit(() => Effect.gen(function* () {
819
+ const database = yield* CurrentD1PlanningDatabase;
820
+ const planned = yield* plan;
821
+ retryable = planned.retryable;
822
+ yield* database.$client.batch(planned.statements);
823
+ return planned.receipt;
824
+ }), { mode: "batch" }).pipe(Effect.map((result) => result.value)).pipe(Effect.catchCause((cause) => retries > 0 && everyFailureMatches(cause, retryable) ? executeStandalone(plan, retries - 1) : Effect.failCause(cause)));
825
+ });
826
+ //#endregion
827
+ export { checkD1ProofCompletion, compileD1ProofCompletionPlan, coordinateD1ProofPersistence, makeD1ProofPersistenceServices };
828
+
829
+ //# sourceMappingURL=d1-proofs.mjs.map