nuxt-backend 0.5.0 → 0.6.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 (414) hide show
  1. package/README.md +8 -4
  2. package/dist/capabilities/registry.js +1 -1
  3. package/dist/chunks/catalog.mjs +1 -1
  4. package/dist/chunks/{index.mjs → devtools.mjs} +2 -2
  5. package/dist/chunks/doctor.mjs +14 -6
  6. package/dist/chunks/email-previews.mjs +1 -1
  7. package/dist/chunks/health.mjs +2 -2
  8. package/dist/chunks/install.mjs +4 -4
  9. package/dist/chunks/run.mjs +1 -1
  10. package/dist/chunks/server.mjs +15 -4
  11. package/dist/cli.mjs +28 -8
  12. package/dist/convex/access-tickets.d.ts +17 -2
  13. package/dist/convex/access-tickets.d.ts.map +1 -1
  14. package/dist/convex/account-data.d.ts +4 -4
  15. package/dist/convex/account-data.d.ts.map +1 -1
  16. package/dist/convex/account-data.js +5 -4
  17. package/dist/convex/account-data.js.map +1 -1
  18. package/dist/convex/app.d.ts +1 -0
  19. package/dist/convex/app.d.ts.map +1 -1
  20. package/dist/convex/app.js +2 -1
  21. package/dist/convex/app.js.map +1 -1
  22. package/dist/convex/client/better-auth-options.d.ts.map +1 -1
  23. package/dist/convex/client/better-auth-options.js +12 -3
  24. package/dist/convex/client/better-auth-options.js.map +1 -1
  25. package/dist/convex/client/component.d.ts +4 -0
  26. package/dist/convex/client/component.d.ts.map +1 -1
  27. package/dist/convex/client/index.d.ts +5 -0
  28. package/dist/convex/client/index.d.ts.map +1 -1
  29. package/dist/convex/client/launch-gate.d.ts.map +1 -1
  30. package/dist/convex/client/launch-gate.js +30 -1
  31. package/dist/convex/client/launch-gate.js.map +1 -1
  32. package/dist/convex/client/plugins.d.ts.map +1 -1
  33. package/dist/convex/client/plugins.js +3 -0
  34. package/dist/convex/client/plugins.js.map +1 -1
  35. package/dist/convex/client/two-factor.d.ts +7 -0
  36. package/dist/convex/client/two-factor.d.ts.map +1 -0
  37. package/dist/convex/client/two-factor.js +57 -0
  38. package/dist/convex/client/two-factor.js.map +1 -0
  39. package/dist/convex/components/backend/_generated/api.d.ts +2 -0
  40. package/dist/convex/components/backend/_generated/api.d.ts.map +1 -1
  41. package/dist/convex/components/backend/_generated/api.js.map +1 -1
  42. package/dist/convex/components/backend/_generated/component.d.ts +292 -10
  43. package/dist/convex/components/backend/_generated/component.d.ts.map +1 -1
  44. package/dist/convex/components/backend/account.d.ts +63 -17
  45. package/dist/convex/components/backend/account.d.ts.map +1 -1
  46. package/dist/convex/components/backend/account.js +24 -1
  47. package/dist/convex/components/backend/account.js.map +1 -1
  48. package/dist/convex/components/backend/adapter.d.ts.map +1 -1
  49. package/dist/convex/components/backend/adapter.js +7 -2
  50. package/dist/convex/components/backend/adapter.js.map +1 -1
  51. package/dist/convex/components/backend/ai.d.ts +1 -1
  52. package/dist/convex/components/backend/billing.d.ts +10 -0
  53. package/dist/convex/components/backend/billing.d.ts.map +1 -1
  54. package/dist/convex/components/backend/billing.js +2 -1
  55. package/dist/convex/components/backend/billing.js.map +1 -1
  56. package/dist/convex/components/backend/commerce.d.ts +229 -0
  57. package/dist/convex/components/backend/commerce.d.ts.map +1 -0
  58. package/dist/convex/components/backend/commerce.js +392 -0
  59. package/dist/convex/components/backend/commerce.js.map +1 -0
  60. package/dist/convex/components/backend/funnel.d.ts +6 -6
  61. package/dist/convex/components/backend/jobs.d.ts +1 -1
  62. package/dist/convex/components/backend/referrals.d.ts +2 -2
  63. package/dist/convex/components/backend/schema.d.ts +327 -21
  64. package/dist/convex/components/backend/schema.d.ts.map +1 -1
  65. package/dist/convex/components/backend/schema.js +108 -1
  66. package/dist/convex/components/backend/schema.js.map +1 -1
  67. package/dist/convex/components/backend/waitlist.d.ts +42 -6
  68. package/dist/convex/components/backend/waitlist.d.ts.map +1 -1
  69. package/dist/convex/components/backend/waitlist.js +142 -39
  70. package/dist/convex/components/backend/waitlist.js.map +1 -1
  71. package/dist/convex/email-templates.d.ts +12 -0
  72. package/dist/convex/email-templates.d.ts.map +1 -1
  73. package/dist/convex/email-templates.js +3 -0
  74. package/dist/convex/email-templates.js.map +1 -1
  75. package/dist/convex/emails/waitlist-friend-joined.d.ts +9 -0
  76. package/dist/convex/emails/waitlist-friend-joined.d.ts.map +1 -0
  77. package/dist/convex/emails/waitlist-friend-joined.js +22 -0
  78. package/dist/convex/emails/waitlist-friend-joined.js.map +1 -0
  79. package/dist/convex/errors.d.ts +6 -6
  80. package/dist/convex/errors.d.ts.map +1 -1
  81. package/dist/convex/errors.js +14 -2
  82. package/dist/convex/errors.js.map +1 -1
  83. package/dist/convex/events.d.ts +19 -0
  84. package/dist/convex/events.d.ts.map +1 -1
  85. package/dist/convex/events.js +14 -0
  86. package/dist/convex/events.js.map +1 -1
  87. package/dist/convex/integrations/billing/checkout.d.ts +2 -2
  88. package/dist/convex/integrations/billing/checkout.d.ts.map +1 -1
  89. package/dist/convex/integrations/billing/checkout.js +79 -11
  90. package/dist/convex/integrations/billing/checkout.js.map +1 -1
  91. package/dist/convex/integrations/billing/commerce-entitlements.d.ts +12 -0
  92. package/dist/convex/integrations/billing/commerce-entitlements.d.ts.map +1 -0
  93. package/dist/convex/integrations/billing/commerce-entitlements.js +78 -0
  94. package/dist/convex/integrations/billing/commerce-entitlements.js.map +1 -0
  95. package/dist/convex/integrations/billing/commerce-events.d.ts +15 -0
  96. package/dist/convex/integrations/billing/commerce-events.d.ts.map +1 -0
  97. package/dist/convex/integrations/billing/commerce-events.js +433 -0
  98. package/dist/convex/integrations/billing/commerce-events.js.map +1 -0
  99. package/dist/convex/integrations/billing/commerce-history.d.ts +20 -0
  100. package/dist/convex/integrations/billing/commerce-history.d.ts.map +1 -0
  101. package/dist/convex/integrations/billing/commerce-history.js +106 -0
  102. package/dist/convex/integrations/billing/commerce-history.js.map +1 -0
  103. package/dist/convex/integrations/billing/commerce-webhooks.d.ts +23 -0
  104. package/dist/convex/integrations/billing/commerce-webhooks.d.ts.map +1 -0
  105. package/dist/convex/integrations/billing/commerce-webhooks.js +49 -0
  106. package/dist/convex/integrations/billing/commerce-webhooks.js.map +1 -0
  107. package/dist/convex/integrations/billing/commerce.d.ts +100 -0
  108. package/dist/convex/integrations/billing/commerce.d.ts.map +1 -0
  109. package/dist/convex/integrations/billing/commerce.js +323 -0
  110. package/dist/convex/integrations/billing/commerce.js.map +1 -0
  111. package/dist/convex/integrations/billing/context.d.ts +8 -0
  112. package/dist/convex/integrations/billing/context.d.ts.map +1 -1
  113. package/dist/convex/integrations/billing/context.js +14 -2
  114. package/dist/convex/integrations/billing/context.js.map +1 -1
  115. package/dist/convex/integrations/billing/credits.d.ts +1 -1
  116. package/dist/convex/integrations/billing/credits.d.ts.map +1 -1
  117. package/dist/convex/integrations/billing/credits.js +49 -28
  118. package/dist/convex/integrations/billing/credits.js.map +1 -1
  119. package/dist/convex/integrations/billing/customers.d.ts +1 -1
  120. package/dist/convex/integrations/billing/customers.d.ts.map +1 -1
  121. package/dist/convex/integrations/billing/customers.js +15 -1
  122. package/dist/convex/integrations/billing/customers.js.map +1 -1
  123. package/dist/convex/integrations/billing/entitlements.d.ts +1 -1
  124. package/dist/convex/integrations/billing/entitlements.d.ts.map +1 -1
  125. package/dist/convex/integrations/billing/entitlements.js +6 -1
  126. package/dist/convex/integrations/billing/entitlements.js.map +1 -1
  127. package/dist/convex/integrations/billing/erasure.d.ts +1 -1
  128. package/dist/convex/integrations/billing/erasure.d.ts.map +1 -1
  129. package/dist/convex/integrations/billing/erasure.js +10 -5
  130. package/dist/convex/integrations/billing/erasure.js.map +1 -1
  131. package/dist/convex/integrations/billing/free-plan.d.ts +6 -1
  132. package/dist/convex/integrations/billing/free-plan.d.ts.map +1 -1
  133. package/dist/convex/integrations/billing/free-plan.js +22 -4
  134. package/dist/convex/integrations/billing/free-plan.js.map +1 -1
  135. package/dist/convex/integrations/billing/functions.d.ts +1 -1
  136. package/dist/convex/integrations/billing/functions.d.ts.map +1 -1
  137. package/dist/convex/integrations/billing/functions.js +3 -2
  138. package/dist/convex/integrations/billing/functions.js.map +1 -1
  139. package/dist/convex/integrations/billing/gifts.d.ts.map +1 -1
  140. package/dist/convex/integrations/billing/gifts.js +3 -0
  141. package/dist/convex/integrations/billing/gifts.js.map +1 -1
  142. package/dist/convex/integrations/billing/history.d.ts +1 -1
  143. package/dist/convex/integrations/billing/history.d.ts.map +1 -1
  144. package/dist/convex/integrations/billing/history.js +6 -1
  145. package/dist/convex/integrations/billing/history.js.map +1 -1
  146. package/dist/convex/integrations/billing/lifecycle.d.ts +1 -1
  147. package/dist/convex/integrations/billing/lifecycle.d.ts.map +1 -1
  148. package/dist/convex/integrations/billing/lifecycle.js +4 -1
  149. package/dist/convex/integrations/billing/lifecycle.js.map +1 -1
  150. package/dist/convex/integrations/billing/providers/capabilities.d.ts +17 -0
  151. package/dist/convex/integrations/billing/providers/capabilities.d.ts.map +1 -0
  152. package/dist/convex/integrations/billing/providers/capabilities.js +77 -0
  153. package/dist/convex/integrations/billing/providers/capabilities.js.map +1 -0
  154. package/dist/convex/integrations/billing/providers/consent.d.ts +52 -0
  155. package/dist/convex/integrations/billing/providers/consent.d.ts.map +1 -0
  156. package/dist/convex/integrations/billing/providers/consent.js +79 -0
  157. package/dist/convex/integrations/billing/providers/consent.js.map +1 -0
  158. package/dist/convex/integrations/billing/providers/creem.d.ts +22 -0
  159. package/dist/convex/integrations/billing/providers/creem.d.ts.map +1 -0
  160. package/dist/convex/integrations/billing/providers/creem.js +208 -0
  161. package/dist/convex/integrations/billing/providers/creem.js.map +1 -0
  162. package/dist/convex/integrations/billing/providers/dodo.d.ts +15 -0
  163. package/dist/convex/integrations/billing/providers/dodo.d.ts.map +1 -0
  164. package/dist/convex/integrations/billing/providers/dodo.js +197 -0
  165. package/dist/convex/integrations/billing/providers/dodo.js.map +1 -0
  166. package/dist/convex/integrations/billing/providers/http.d.ts +41 -0
  167. package/dist/convex/integrations/billing/providers/http.d.ts.map +1 -0
  168. package/dist/convex/integrations/billing/providers/http.js +146 -0
  169. package/dist/convex/integrations/billing/providers/http.js.map +1 -0
  170. package/dist/convex/integrations/billing/providers/index.d.ts +35 -0
  171. package/dist/convex/integrations/billing/providers/index.d.ts.map +1 -0
  172. package/dist/convex/integrations/billing/providers/index.js +62 -0
  173. package/dist/convex/integrations/billing/providers/index.js.map +1 -0
  174. package/dist/convex/integrations/billing/providers/stripe.d.ts +28 -0
  175. package/dist/convex/integrations/billing/providers/stripe.d.ts.map +1 -0
  176. package/dist/convex/integrations/billing/providers/stripe.js +327 -0
  177. package/dist/convex/integrations/billing/providers/stripe.js.map +1 -0
  178. package/dist/convex/integrations/billing/providers/types.d.ts +263 -0
  179. package/dist/convex/integrations/billing/providers/types.d.ts.map +1 -0
  180. package/dist/convex/integrations/billing/providers/types.js +48 -0
  181. package/dist/convex/integrations/billing/providers/types.js.map +1 -0
  182. package/dist/convex/integrations/billing/subscriptions.d.ts +1 -1
  183. package/dist/convex/integrations/billing/subscriptions.d.ts.map +1 -1
  184. package/dist/convex/integrations/billing/subscriptions.js +20 -6
  185. package/dist/convex/integrations/billing/subscriptions.js.map +1 -1
  186. package/dist/convex/integrations/billing/types/setup.d.ts +64 -1
  187. package/dist/convex/integrations/billing/types/setup.d.ts.map +1 -1
  188. package/dist/convex/integrations/billing.d.ts +4 -1
  189. package/dist/convex/integrations/billing.d.ts.map +1 -1
  190. package/dist/convex/integrations/billing.js +12 -2
  191. package/dist/convex/integrations/billing.js.map +1 -1
  192. package/dist/convex/integrations/email.d.ts +1 -1
  193. package/dist/convex/integrations/email.d.ts.map +1 -1
  194. package/dist/convex/integrations/email.js.map +1 -1
  195. package/dist/convex/integrations/launch.d.ts +27 -2
  196. package/dist/convex/integrations/launch.d.ts.map +1 -1
  197. package/dist/convex/integrations/launch.js +15 -3
  198. package/dist/convex/integrations/launch.js.map +1 -1
  199. package/dist/convex/integrations/presence.d.ts +110 -0
  200. package/dist/convex/integrations/presence.d.ts.map +1 -0
  201. package/dist/convex/integrations/presence.js +92 -0
  202. package/dist/convex/integrations/presence.js.map +1 -0
  203. package/dist/convex/integrations/waitlist.d.ts +41 -7
  204. package/dist/convex/integrations/waitlist.d.ts.map +1 -1
  205. package/dist/convex/integrations/waitlist.js +45 -6
  206. package/dist/convex/integrations/waitlist.js.map +1 -1
  207. package/dist/convex/integrations/webhook-guard.d.ts +8 -0
  208. package/dist/convex/integrations/webhook-guard.d.ts.map +1 -1
  209. package/dist/convex/integrations/webhook-guard.js +11 -4
  210. package/dist/convex/integrations/webhook-guard.js.map +1 -1
  211. package/dist/convex/label-groups/admin.d.ts +9 -0
  212. package/dist/convex/label-groups/admin.d.ts.map +1 -1
  213. package/dist/convex/label-groups/admin.js +9 -0
  214. package/dist/convex/label-groups/admin.js.map +1 -1
  215. package/dist/convex/label-groups/audit.d.ts +2 -0
  216. package/dist/convex/label-groups/audit.d.ts.map +1 -1
  217. package/dist/convex/label-groups/audit.js +2 -0
  218. package/dist/convex/label-groups/audit.js.map +1 -1
  219. package/dist/convex/label-groups/auth.d.ts +9 -0
  220. package/dist/convex/label-groups/auth.d.ts.map +1 -1
  221. package/dist/convex/label-groups/auth.js +10 -0
  222. package/dist/convex/label-groups/auth.js.map +1 -1
  223. package/dist/convex/label-groups/email.d.ts +6 -0
  224. package/dist/convex/label-groups/email.d.ts.map +1 -1
  225. package/dist/convex/label-groups/email.js +7 -0
  226. package/dist/convex/label-groups/email.js.map +1 -1
  227. package/dist/convex/label-groups/errors.d.ts +4 -0
  228. package/dist/convex/label-groups/errors.d.ts.map +1 -1
  229. package/dist/convex/label-groups/errors.js +4 -0
  230. package/dist/convex/label-groups/errors.js.map +1 -1
  231. package/dist/convex/label-groups/security.d.ts +19 -0
  232. package/dist/convex/label-groups/security.d.ts.map +1 -1
  233. package/dist/convex/label-groups/security.js +20 -0
  234. package/dist/convex/label-groups/security.js.map +1 -1
  235. package/dist/convex/label-groups/waitlist.d.ts +8 -0
  236. package/dist/convex/label-groups/waitlist.d.ts.map +1 -1
  237. package/dist/convex/label-groups/waitlist.js +9 -0
  238. package/dist/convex/label-groups/waitlist.js.map +1 -1
  239. package/dist/convex/label-translations.d.ts.map +1 -1
  240. package/dist/convex/label-translations.js +24 -0
  241. package/dist/convex/label-translations.js.map +1 -1
  242. package/dist/convex/labels.d.ts +57 -0
  243. package/dist/convex/labels.d.ts.map +1 -1
  244. package/dist/convex/log.js +2 -0
  245. package/dist/convex/log.js.map +1 -1
  246. package/dist/convex/sensitive-actions.d.ts.map +1 -1
  247. package/dist/convex/sensitive-actions.js +11 -0
  248. package/dist/convex/sensitive-actions.js.map +1 -1
  249. package/dist/convex/waitlist-rules.d.ts +63 -9
  250. package/dist/convex/waitlist-rules.d.ts.map +1 -1
  251. package/dist/convex/waitlist-rules.js +38 -7
  252. package/dist/convex/waitlist-rules.js.map +1 -1
  253. package/dist/devtools-client/_nuxt/DHNi4uhO.js +6 -0
  254. package/dist/devtools-client/index.html +1 -1
  255. package/dist/env-registry.js +9 -0
  256. package/dist/module.d.ts +14 -2
  257. package/dist/module.js +2 -2
  258. package/dist/module.json +2 -2
  259. package/dist/runtime/locales/de.json +58 -1
  260. package/dist/runtime/locales/en.json +60 -3
  261. package/dist/runtime/locales/es.json +58 -1
  262. package/dist/runtime/locales/fr.json +58 -1
  263. package/dist/runtime/locales/ru.json +58 -1
  264. package/dist/runtime/server/monitoring/backend-calls.d.ts +3 -3
  265. package/dist/runtime/server/monitoring/backend-calls.js +2 -2
  266. package/dist/runtime/server/monitoring/health.js +2 -2
  267. package/dist/runtime/vue/auth-client.d.ts +3 -2
  268. package/dist/runtime/vue/auth-client.js +2 -1
  269. package/dist/runtime/vue/components/account/SecuritySettings.d.vue.ts +25 -2
  270. package/dist/runtime/vue/components/account/SecuritySettings.vue +52 -2
  271. package/dist/runtime/vue/components/account/SecuritySettings.vue.d.ts +25 -2
  272. package/dist/runtime/vue/components/account/SecurityTwoFactor.css +1 -0
  273. package/dist/runtime/vue/components/account/SecurityTwoFactor.d.vue.ts +4 -0
  274. package/dist/runtime/vue/components/account/SecurityTwoFactor.vue +107 -0
  275. package/dist/runtime/vue/components/account/SecurityTwoFactor.vue.d.ts +4 -0
  276. package/dist/runtime/vue/components/account/security-settings.d.ts +18 -1
  277. package/dist/runtime/vue/components/admin/AdminUsers.d.vue.ts +11 -2
  278. package/dist/runtime/vue/components/admin/AdminUsers.vue.d.ts +11 -2
  279. package/dist/runtime/vue/components/admin/AdminWaitlist.css +1 -1
  280. package/dist/runtime/vue/components/admin/AdminWaitlistActions.vue +41 -1
  281. package/dist/runtime/vue/components/admin/AdminWorkspaces.d.vue.ts +9 -0
  282. package/dist/runtime/vue/components/admin/AdminWorkspaces.vue.d.ts +9 -0
  283. package/dist/runtime/vue/components/admin/admin-waitlist-tab.js +28 -0
  284. package/dist/runtime/vue/components/auth/AuthForm.d.vue.ts +9 -0
  285. package/dist/runtime/vue/components/auth/AuthForm.vue +8 -0
  286. package/dist/runtime/vue/components/auth/AuthForm.vue.d.ts +9 -0
  287. package/dist/runtime/vue/components/auth/AuthFormTwoFactor.css +1 -0
  288. package/dist/runtime/vue/components/auth/AuthFormTwoFactor.d.vue.ts +3 -0
  289. package/dist/runtime/vue/components/auth/AuthFormTwoFactor.vue +70 -0
  290. package/dist/runtime/vue/components/auth/AuthFormTwoFactor.vue.d.ts +3 -0
  291. package/dist/runtime/vue/components/auth/AuthFormWaitlisted.vue +7 -2
  292. package/dist/runtime/vue/components/auth/WaitlistForm.d.vue.ts +8 -0
  293. package/dist/runtime/vue/components/auth/WaitlistForm.vue.d.ts +8 -0
  294. package/dist/runtime/vue/components/auth/WaitlistPlace.css +1 -1
  295. package/dist/runtime/vue/components/auth/WaitlistPlace.vue +37 -0
  296. package/dist/runtime/vue/components/auth/WaitlistShare.vue +2 -2
  297. package/dist/runtime/vue/components/auth/auth-form.d.ts +2 -0
  298. package/dist/runtime/vue/components/workspaces/AuditLog.d.vue.ts +2 -0
  299. package/dist/runtime/vue/components/workspaces/AuditLog.vue.d.ts +2 -0
  300. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.d.vue.ts +2 -2
  301. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.vue.d.ts +2 -2
  302. package/dist/runtime/vue/composables/use-login-flow.d.ts +19 -4
  303. package/dist/runtime/vue/composables/use-login-flow.js +31 -0
  304. package/dist/runtime/vue/composables/use-room-presence.d.ts +63 -0
  305. package/dist/runtime/vue/composables/use-room-presence.js +31 -0
  306. package/dist/runtime/vue/composables/use-two-factor.d.ts +58 -0
  307. package/dist/runtime/vue/composables/use-two-factor.js +49 -0
  308. package/dist/runtime/vue/composables/use-waitlist-admin.d.ts +5 -0
  309. package/dist/runtime/vue/composables/use-waitlist-admin.js +5 -1
  310. package/dist/runtime/vue/composables/use-waitlist.d.ts +4 -0
  311. package/dist/runtime/vue/composables/use-waitlist.js +1 -1
  312. package/dist/runtime/vue/parts.d.ts +8 -1
  313. package/dist/runtime/vue/two-factor-client.d.ts +15 -0
  314. package/dist/runtime/vue/two-factor-client.js +19 -0
  315. package/dist/runtime/vue/utils/auth-session.js +10 -1
  316. package/dist/runtime/vue/utils/login-bindings.js +1 -0
  317. package/dist/runtime/vue/utils/page-guard.d.ts +2 -2
  318. package/dist/runtime/vue/utils/page-guard.js +2 -2
  319. package/dist/shared/{nuxt-backend.CBvrM7pG.mjs → nuxt-backend.CM_p0XQE.mjs} +1 -1
  320. package/dist/shared/{nuxt-backend.Dikfaocl.mjs → nuxt-backend.C_Y_BtBs.mjs} +128 -5
  321. package/dist/shared/{nuxt-backend.DbaXvH__.mjs → nuxt-backend.ChvlbHQq.mjs} +203 -9
  322. package/dist/shared/{nuxt-backend.BqXAZChe.mjs → nuxt-backend.D16peTIt.mjs} +57 -35
  323. package/dist/shared/{nuxt-backend.DH1Ya3uB.mjs → nuxt-backend.D4JXvCP6.mjs} +3 -2
  324. package/dist/types.d.ts +1 -1
  325. package/package.json +19 -10
  326. package/skills/nuxt-backend/SKILL.md +18 -18
  327. package/skills/nuxt-backend/references/api.md +31 -6
  328. package/skills/nuxt-backend/references/install.md +9 -6
  329. package/skills/nuxt-backend/references/renames.json +8 -0
  330. package/skills/nuxt-backend/references/surface.json +62 -2
  331. package/skills/nuxt-backend-auth/SKILL.md +8 -2
  332. package/skills/nuxt-backend-auth/references/api.md +3 -1
  333. package/skills/nuxt-backend-billing/SKILL.md +15 -0
  334. package/skills/nuxt-backend-billing/references/api.md +14 -1
  335. package/skills/nuxt-backend-data/SKILL.md +1 -0
  336. package/skills/nuxt-backend-data/references/api.md +10 -1
  337. package/skills/nuxt-backend-email/references/api.md +1 -1
  338. package/skills/nuxt-backend-ship/SKILL.md +2 -1
  339. package/skills/nuxt-backend-upgrade/references/upgrade.md +6 -0
  340. package/src/convex/access-tickets.ts +10 -2
  341. package/src/convex/account-data.ts +5 -4
  342. package/src/convex/app.ts +2 -1
  343. package/src/convex/client/better-auth-options.ts +12 -3
  344. package/src/convex/client/launch-gate.ts +28 -1
  345. package/src/convex/client/plugins.ts +3 -0
  346. package/src/convex/client/two-factor.ts +66 -0
  347. package/src/convex/components/backend/_generated/api.ts +2 -0
  348. package/src/convex/components/backend/_generated/component.ts +500 -2
  349. package/src/convex/components/backend/account.ts +25 -1
  350. package/src/convex/components/backend/adapter.ts +7 -2
  351. package/src/convex/components/backend/billing.ts +2 -1
  352. package/src/convex/components/backend/commerce.ts +408 -0
  353. package/src/convex/components/backend/schema.ts +110 -1
  354. package/src/convex/components/backend/waitlist.ts +144 -40
  355. package/src/convex/email-templates.ts +16 -0
  356. package/src/convex/emails/waitlist-friend-joined.ts +23 -0
  357. package/src/convex/errors.ts +15 -2
  358. package/src/convex/events.ts +14 -0
  359. package/src/convex/integrations/billing/checkout.ts +78 -11
  360. package/src/convex/integrations/billing/commerce-entitlements.ts +92 -0
  361. package/src/convex/integrations/billing/commerce-events.ts +487 -0
  362. package/src/convex/integrations/billing/commerce-history.ts +110 -0
  363. package/src/convex/integrations/billing/commerce-webhooks.ts +69 -0
  364. package/src/convex/integrations/billing/commerce.ts +366 -0
  365. package/src/convex/integrations/billing/context.ts +19 -2
  366. package/src/convex/integrations/billing/credits.ts +47 -27
  367. package/src/convex/integrations/billing/customers.ts +15 -1
  368. package/src/convex/integrations/billing/entitlements.ts +5 -1
  369. package/src/convex/integrations/billing/erasure.ts +11 -6
  370. package/src/convex/integrations/billing/free-plan.ts +30 -5
  371. package/src/convex/integrations/billing/functions.ts +3 -2
  372. package/src/convex/integrations/billing/gifts.ts +2 -0
  373. package/src/convex/integrations/billing/history.ts +9 -0
  374. package/src/convex/integrations/billing/lifecycle.ts +3 -1
  375. package/src/convex/integrations/billing/providers/capabilities.ts +78 -0
  376. package/src/convex/integrations/billing/providers/consent.ts +94 -0
  377. package/src/convex/integrations/billing/providers/creem.ts +225 -0
  378. package/src/convex/integrations/billing/providers/dodo.ts +214 -0
  379. package/src/convex/integrations/billing/providers/http.ts +168 -0
  380. package/src/convex/integrations/billing/providers/index.ts +65 -0
  381. package/src/convex/integrations/billing/providers/stripe.ts +345 -0
  382. package/src/convex/integrations/billing/providers/types.ts +281 -0
  383. package/src/convex/integrations/billing/subscriptions.ts +20 -6
  384. package/src/convex/integrations/billing/types/setup.ts +63 -1
  385. package/src/convex/integrations/billing.ts +46 -3
  386. package/src/convex/integrations/email.ts +1 -0
  387. package/src/convex/integrations/launch.ts +45 -7
  388. package/src/convex/integrations/presence.ts +160 -0
  389. package/src/convex/integrations/waitlist.ts +84 -12
  390. package/src/convex/integrations/webhook-guard.ts +20 -4
  391. package/src/convex/label-groups/admin.ts +9 -0
  392. package/src/convex/label-groups/audit.ts +2 -0
  393. package/src/convex/label-groups/auth.ts +10 -0
  394. package/src/convex/label-groups/email.ts +7 -0
  395. package/src/convex/label-groups/errors.ts +4 -0
  396. package/src/convex/label-groups/security.ts +20 -0
  397. package/src/convex/label-groups/waitlist.ts +9 -0
  398. package/src/convex/label-translations.ts +24 -0
  399. package/src/convex/log.ts +2 -0
  400. package/src/convex/sensitive-actions.ts +11 -0
  401. package/src/convex/waitlist-rules.ts +84 -8
  402. package/src/runtime/vue/components/account/SecuritySettings.vue +58 -4
  403. package/src/runtime/vue/components/account/SecurityTwoFactor.css +68 -0
  404. package/src/runtime/vue/components/account/SecurityTwoFactor.vue +113 -0
  405. package/src/runtime/vue/components/admin/AdminWaitlist.css +1 -0
  406. package/src/runtime/vue/components/admin/AdminWaitlistActions.vue +44 -2
  407. package/src/runtime/vue/components/auth/AuthForm.vue +8 -0
  408. package/src/runtime/vue/components/auth/AuthFormTwoFactor.css +40 -0
  409. package/src/runtime/vue/components/auth/AuthFormTwoFactor.vue +75 -0
  410. package/src/runtime/vue/components/auth/AuthFormWaitlisted.vue +11 -4
  411. package/src/runtime/vue/components/auth/WaitlistPlace.css +16 -0
  412. package/src/runtime/vue/components/auth/WaitlistPlace.vue +49 -2
  413. package/src/runtime/vue/components/auth/WaitlistShare.vue +4 -3
  414. package/dist/devtools-client/_nuxt/CiCAOwUc.js +0 -5
@@ -202,7 +202,7 @@ export const ERASURE_PARTICIPANTS = {
202
202
  return budget.spent
203
203
  },
204
204
 
205
- // The account, its sessions, sign-in accounts and passkeys, and the codes
205
+ // The account, its sessions, sign-in accounts, passkeys and authenticator app, and the codes
206
206
  // waiting for its address. Better Auth deleted the first three already
207
207
  // when it deleted the account; an erasure that starts here deletes them.
208
208
  auth: async (ctx, { userId, email }) => {
@@ -211,6 +211,9 @@ export const ERASURE_PARTICIPANTS = {
211
211
  await budget.remove(ctx, 'session', () => ctx.db.query('session').withIndex('userId', q => q.eq('userId', userId)).take(budget.left))
212
212
  await budget.remove(ctx, 'account', () => ctx.db.query('account').withIndex('userId', q => q.eq('userId', userId)).take(budget.left))
213
213
  await budget.remove(ctx, 'passkey', () => ctx.db.query('passkey').withIndex('userId', q => q.eq('userId', userId)).take(budget.left))
214
+ await budget.remove(ctx, 'twoFactor', () => ctx.db.query('twoFactor').withIndex('userId', q => q.eq('userId', userId)).take(budget.left))
215
+ // The devices the authenticator app trusts: each row holds the account's id as its value.
216
+ await budget.remove(ctx, 'verification', async () => (await ctx.db.query('verification').withIndex('value', q => q.eq('value', userId)).take(budget.left)).filter(row => row.identifier.startsWith('trust-device-')))
214
217
  }
215
218
  if (email) {
216
219
  for (const identifier of [`sign-in-otp-${email}`, `email-verification-otp-${email}`, `forget-password-otp-${email}`]) {
@@ -255,6 +258,9 @@ export const ERASURE_PARTICIPANTS = {
255
258
  await budget.remove(ctx, 'billingDiscountAttempts', () => ctx.db.query('billingDiscountAttempts').withIndex('userId', q => q.eq('userId', entityId)).take(budget.left))
256
259
  await budget.remove(ctx, 'billingQuotaKeys', () => ctx.db.query('billingQuotaKeys').withIndex('userId_key', q => q.eq('userId', entityId)).take(budget.left))
257
260
  await budget.remove(ctx, 'billingSaveOffers', () => ctx.db.query('billingSaveOffers').withIndex('entityId_madeAt', q => q.eq('entityId', entityId)).take(budget.left))
261
+ await budget.remove(ctx, 'billingCommerceCustomers', () => ctx.db.query('billingCommerceCustomers').withIndex('entityId_provider', q => q.eq('entityId', entityId)).take(budget.left))
262
+ await budget.remove(ctx, 'billingCommerceOrders', () => ctx.db.query('billingCommerceOrders').withIndex('entityId_createdAt', q => q.eq('entityId', entityId)).take(budget.left))
263
+ await budget.remove(ctx, 'billingCreditGrants', () => ctx.db.query('billingCreditGrants').withIndex('userId_meterId', q => q.eq('userId', entityId)).take(budget.left))
258
264
  }
259
265
  const { userId } = erasure
260
266
  if (userId) await budget.remove(ctx, 'billingTrials', () => ctx.db.query('billingTrials').withIndex('ownerUserId', q => q.eq('ownerUserId', userId)).take(budget.left))
@@ -896,6 +902,20 @@ async function giftsReceived(ctx: QueryCtx, email: string) {
896
902
  return rows.map(({ discountId: _discount, purchaserEmail: _email, purchaserUserId: _user, purchaserEntityId: _entity, billingCustomerId: _customer, billingOrderId: _order, giftProductId: _product, amount: _amount, currency: _currency, ...gift }) => exported(gift))
897
903
  }
898
904
 
905
+ /**
906
+ * What an adapter provider (Stripe, Dodo, Creem) left here for the account's
907
+ * billing entities: their customer ids there, their paid orders and the
908
+ * credit grants those made. Empty on Polar, which keeps all three itself.
909
+ */
910
+ async function commerceRows(ctx: QueryCtx, entities: readonly string[]) {
911
+ const each = async <T>(read: (entityId: string) => Promise<T[]>) => (await Promise.all(entities.map(read))).flat()
912
+ return {
913
+ billingCustomers: (await each(entityId => ctx.db.query('billingCommerceCustomers').withIndex('entityId_provider', q => q.eq('entityId', entityId)).take(MEMBERSHIPS_MAX))).map(exported),
914
+ billingOrders: (await each(entityId => ctx.db.query('billingCommerceOrders').withIndex('entityId_createdAt', q => q.eq('entityId', entityId)).take(MEMBERSHIPS_MAX))).map(exported),
915
+ billingCreditGrants: (await each(entityId => ctx.db.query('billingCreditGrants').withIndex('userId_meterId', q => q.eq('userId', entityId)).take(MEMBERSHIPS_MAX))).map(exported),
916
+ }
917
+ }
918
+
899
919
  /**
900
920
  * What the component keeps of an account, for its export: the account,
901
921
  * its sessions, sign-in accounts and passkeys, its workspaces and
@@ -932,6 +952,9 @@ export const exportData = query({
932
952
  .map(({ accessToken: _a, refreshToken: _r, idToken: _i, password: _p, ...row }) => exported(row)),
933
953
  passkeys: (await ctx.db.query('passkey').withIndex('userId', q => q.eq('userId', userId)).take(MEMBERSHIPS_MAX))
934
954
  .map(({ publicKey: _key, credentialID: _credential, counter: _counter, ...passkey }) => exported(passkey)),
955
+ // Whether the authenticator app is on, never its secret or its backup codes.
956
+ authenticatorApps: (await ctx.db.query('twoFactor').withIndex('userId', q => q.eq('userId', userId)).take(MEMBERSHIPS_MAX))
957
+ .map(({ secret: _secret, backupCodes: _codes, ...row }) => exported(row)),
935
958
  workspaces,
936
959
  consents: await consentRows(ctx, userId),
937
960
  ...await inboundRows(ctx, userId),
@@ -947,6 +970,7 @@ export const exportData = query({
947
970
  billing: (await Promise.all(entities.map(entityId => ctx.db.query('billingEntitlements').withIndex('userId', q => q.eq('userId', entityId)).first())))
948
971
  .filter(row => row !== null)
949
972
  .map(row => exported(row)),
973
+ ...await commerceRows(ctx, entities),
950
974
  // A deletion waiting out its grace period, when there is one.
951
975
  deletion: await ctx.db.query('accountDeletions').withIndex('userId', q => q.eq('userId', userId)).first().then(row => row ? { requestedAt: row.requestedAt, deletesAt: row.deletesAt } : null),
952
976
  activity: (await ctx.db.query('auditEvents').withIndex('subjectId_at', q => q.eq('subjectId', userId)).order('desc').take(EXPORT_ACTIVITY_MAX)).map(exported),
@@ -1,12 +1,13 @@
1
1
  import { passkey } from '@better-auth/passkey'
2
2
  import type { BetterAuthOptions } from 'better-auth/minimal'
3
- import { admin, emailOTP, lastLoginMethod, organization } from 'better-auth/plugins'
3
+ import { admin, emailOTP, lastLoginMethod, organization, twoFactor } from 'better-auth/plugins'
4
4
  import { createApi } from '@convex-dev/better-auth'
5
5
  import { convex } from '@convex-dev/better-auth/plugins'
6
6
  import type { RegisteredMutation, RegisteredQuery } from 'convex/server'
7
7
  import { ACCOUNT_FIELDS, PASSKEY_ONLY_PLUGIN, SESSION_FIELDS } from '../../client/plugins.js'
8
8
  import { CLIENT_ADDRESS_PLUGIN_ID } from '../../client/client-address.js'
9
9
  import { SECRET_ROTATION_PLUGIN_ID } from '../../client/secret-rotation.js'
10
+ import { TWO_FACTOR_STEP_PLUGIN_ID } from '../../client/two-factor.js'
10
11
  import { authSchema as schema } from './schema.js'
11
12
 
12
13
  /**
@@ -14,7 +15,7 @@ import { authSchema as schema } from './schema.js'
14
15
  * component adapter. Mirrors upstream @convex-dev/better-auth component/adapter
15
16
  * pattern (see their auth-options.ts + adapter.ts) but limited to plugins we
16
17
  * enable by default (convex + emailOTP + passkey + lastLoginMethod + admin +
17
- * organization + passkey-only + the secret rotation + the client address) for minimal surface. ⚠ Keep this
18
+ * organization + two-factor + passkey-only + the secret rotation + the client address) for minimal surface. ⚠ Keep this
18
19
  * plugin set aligned with the default set `buildAuthOptions` builds
19
20
  * (src/convex/client/better-auth-options.ts) —
20
21
  * a plugin enabled there but missing here leaves its tables out of the
@@ -36,6 +37,10 @@ const options: BetterAuthOptions = {
36
37
  lastLoginMethod({ storeInDatabase: true }),
37
38
  admin(),
38
39
  organization(),
40
+ // The authenticator app: the account's switch, its secret and backup codes.
41
+ twoFactor(),
42
+ // Its second step after a sign-in code: no tables.
43
+ { id: TWO_FACTOR_STEP_PLUGIN_ID },
39
44
  // Passkey-only accounts: the account's switch and recovery code, the recovery session's mark.
40
45
  { id: PASSKEY_ONLY_PLUGIN.id, schema: PASSKEY_ONLY_PLUGIN.schema },
41
46
  // The AUTH_SECRET rotation's cookie re-signing: no tables.
@@ -51,7 +51,8 @@ function keepPendingCredits(meters: Array<typeof vEntitlementMeter.type>, cached
51
51
  return kept
52
52
  }
53
53
 
54
- function activePendings(pendings: PendingSpend[] | undefined, now: number): PendingSpend[] {
54
+ /** The reservations still in force: a held one until its time, else ten minutes. */
55
+ export function activePendings(pendings: PendingSpend[] | undefined, now: number): PendingSpend[] {
55
56
  return (pendings ?? []).filter(pending => pending.until === undefined ? now - pending.at < PENDING_SPEND_TTL_MS : now < pending.until)
56
57
  }
57
58
 
@@ -0,0 +1,408 @@
1
+ import { paginationOptsValidator } from 'convex/server'
2
+ import { v } from 'convex/values'
3
+ import type { Doc } from './_generated/dataModel.js'
4
+ import { type MutationCtx, mutation, query, type QueryCtx } from './_generated/server.js'
5
+ import { activePendings } from './billing.js'
6
+ import { retierOwner } from './jobs.js'
7
+ import { commerceOrderFields, vCommerceOrderStatus, vEntitlementBenefit } from './schema.js'
8
+
9
+ /**
10
+ * The records a billing provider on the neutral adapters (Stripe Managed
11
+ * Payments, Dodo, Creem) leaves to the app: which customer each billing
12
+ * entity is at the provider, the orders it paid, and its credit grants. On
13
+ * Polar the provider keeps all three (its customers, orders and meters);
14
+ * here no provider meter exists, so the entitlement cache's balance is the
15
+ * record, and every grant lands once by its `externalId`.
16
+ *
17
+ * Public component functions, like the rest of the cache: only the parent
18
+ * app reaches them, through `components.backend.commerce.*`.
19
+ */
20
+
21
+ const vOrder = v.object({ ...commerceOrderFields, status: vCommerceOrderStatus, refundedAmount: v.number(), createdAt: v.number() })
22
+
23
+ /** An order's row by its id, or `null`. */
24
+ function orderRow(ctx: { db: QueryCtx['db'] }, orderId: string) {
25
+ return ctx.db.query('billingCommerceOrders').withIndex('orderId', q => q.eq('orderId', orderId)).first()
26
+ }
27
+
28
+ /** An order row as the app reads it: without the refund ids and the system fields. */
29
+ function orderOf(row: Doc<'billingCommerceOrders'>): typeof vOrder.type {
30
+ const { _id: _ignored, _creationTime: _time, refundIds: _refunds, ...order } = row
31
+ return order
32
+ }
33
+
34
+ /** An order row as the app reads it, or `null` for none. */
35
+ function orderOrNull(row: Doc<'billingCommerceOrders'> | null): typeof vOrder.type | null {
36
+ return row ? orderOf(row) : null
37
+ }
38
+
39
+ /** The entity's customer at `provider`, or `null`. */
40
+ export const customerOf = query({
41
+ args: { entityId: v.string(), provider: v.string() },
42
+ returns: v.union(v.string(), v.null()),
43
+ handler: async (ctx, { entityId, provider }) =>
44
+ (await ctx.db.query('billingCommerceCustomers').withIndex('entityId_provider', q => q.eq('entityId', entityId).eq('provider', provider)).first())?.customerId ?? null,
45
+ })
46
+
47
+ /** The entity a provider customer belongs to, or `null` for one no checkout of the app made. */
48
+ export const entityOfCustomer = query({
49
+ args: { provider: v.string(), customerId: v.string() },
50
+ returns: v.union(v.string(), v.null()),
51
+ handler: async (ctx, { provider, customerId }) =>
52
+ (await ctx.db.query('billingCommerceCustomers').withIndex('provider_customerId', q => q.eq('provider', provider).eq('customerId', customerId)).first())?.entityId ?? null,
53
+ })
54
+
55
+ /**
56
+ * Note the entity's customer at the provider, from a delivery that names
57
+ * both. The latest one wins: a provider that made a second customer for a
58
+ * checkout that named none is the one the portal opens next.
59
+ */
60
+ export const linkCustomer = mutation({
61
+ args: { entityId: v.string(), provider: v.string(), customerId: v.string() },
62
+ returns: v.null(),
63
+ handler: async (ctx, { entityId, provider, customerId }) => {
64
+ const existing = await ctx.db.query('billingCommerceCustomers').withIndex('entityId_provider', q => q.eq('entityId', entityId).eq('provider', provider)).first()
65
+ if (!existing) await ctx.db.insert('billingCommerceCustomers', { entityId, provider, customerId })
66
+ else if (existing.customerId !== customerId) await ctx.db.patch('billingCommerceCustomers', existing._id, { customerId })
67
+ return null
68
+ },
69
+ })
70
+
71
+ /** Where an order stands with `amount` more refunded (all of what is left when it names none). */
72
+ function refunded(row: Pick<Doc<'billingCommerceOrders'>, 'amount' | 'refundedAmount'>, amount: number | undefined) {
73
+ const refundedAmount = Math.min(row.amount, row.refundedAmount + (amount === undefined || !Number.isFinite(amount) ? row.amount : Math.max(0, amount)))
74
+ return { refundedAmount, status: refundedAmount >= row.amount ? 'refunded' as const : 'partially_refunded' as const }
75
+ }
76
+
77
+ /**
78
+ * Record a paid order once: `false` for one recorded before (a
79
+ * redelivery). The refunds and the dispute held for it, which arrived
80
+ * first, apply as it lands, in the order they came: a dispute keeps the
81
+ * order disputed whatever is refunded with it, so its credits go back.
82
+ */
83
+ export const recordOrder = mutation({
84
+ args: commerceOrderFields,
85
+ returns: v.boolean(),
86
+ handler: async (ctx, order) => {
87
+ const existing = await orderRow(ctx, order.orderId)
88
+ if (existing) return false
89
+ let row: Omit<Doc<'billingCommerceOrders'>, '_id' | '_creationTime'> = { ...order, status: 'paid', refundedAmount: 0, refundIds: [], createdAt: Date.now() }
90
+ for await (const reversal of ctx.db.query('billingCommerceReversals').withIndex('orderId', q => q.eq('orderId', order.orderId))) {
91
+ if (reversal.kind === 'dispute') row = { ...row, status: 'disputed' }
92
+ else if (!row.refundIds.includes(reversal.refundId)) {
93
+ const next = refunded(row, reversal.amount)
94
+ row = { ...row, refundedAmount: next.refundedAmount, status: row.status === 'disputed' ? 'disputed' : next.status, refundIds: [...row.refundIds, reversal.refundId] }
95
+ }
96
+ await ctx.db.delete('billingCommerceReversals', reversal._id)
97
+ }
98
+ await ctx.db.insert('billingCommerceOrders', row)
99
+ return true
100
+ },
101
+ })
102
+
103
+ /**
104
+ * Hold a refund or a dispute that names an order not recorded yet, for
105
+ * the order to apply as it lands (`recordOrder`). Answers `false` when the
106
+ * order is recorded by now: the caller moves it as it would any other.
107
+ */
108
+ export const holdReversal = mutation({
109
+ args: { orderId: v.string(), kind: v.union(v.literal('refund'), v.literal('dispute')), refundId: v.optional(v.string()), amount: v.optional(v.number()) },
110
+ returns: v.boolean(),
111
+ handler: async (ctx, { orderId, kind, refundId, amount }) => {
112
+ if (await orderRow(ctx, orderId)) return false
113
+ const id = kind === 'dispute' ? 'dispute' : refundId ?? 'refund'
114
+ for await (const held of ctx.db.query('billingCommerceReversals').withIndex('orderId', q => q.eq('orderId', orderId))) {
115
+ if (held.refundId === id) return true
116
+ }
117
+ await ctx.db.insert('billingCommerceReversals', { orderId, kind, refundId: id, ...(amount === undefined ? {} : { amount }), at: Date.now() })
118
+ return true
119
+ },
120
+ })
121
+
122
+ /** One order by its id, or `null`. */
123
+ export const getOrder = query({
124
+ args: { orderId: v.string() },
125
+ returns: v.union(vOrder, v.null()),
126
+ handler: async (ctx, { orderId }) => orderOrNull(await orderRow(ctx, orderId)),
127
+ })
128
+
129
+ /** An entity's orders, newest first, a page at a time. */
130
+ export const listOrders = query({
131
+ args: { entityId: v.string(), paginationOpts: paginationOptsValidator },
132
+ returns: v.object({ page: v.array(vOrder), isDone: v.boolean(), continueCursor: v.string() }),
133
+ handler: async (ctx, { entityId, paginationOpts }) => {
134
+ const read = await ctx.db.query('billingCommerceOrders').withIndex('entityId_createdAt', q => q.eq('entityId', entityId)).order('desc').paginate(paginationOpts)
135
+ return { page: read.page.map(orderOf), isDone: read.isDone, continueCursor: read.continueCursor }
136
+ },
137
+ })
138
+
139
+ /**
140
+ * Count a refund against its order, once per refund id. Answers the order
141
+ * as it now stands and whether this refund was new; `null` for an order
142
+ * the app never recorded.
143
+ */
144
+ export const refundOrder = mutation({
145
+ args: { orderId: v.string(), refundId: v.string(), amount: v.optional(v.number()) },
146
+ returns: v.union(v.object({ order: vOrder, counted: v.boolean() }), v.null()),
147
+ handler: async (ctx, { orderId, refundId, amount }) => {
148
+ const row = await orderRow(ctx, orderId)
149
+ if (!row) return null
150
+ if (row.refundIds.includes(refundId)) return { order: orderOf(row), counted: false }
151
+ const { refundedAmount, status } = refunded(row, amount)
152
+ await ctx.db.patch('billingCommerceOrders', row._id, { refundedAmount, status, refundIds: [...row.refundIds, refundId] })
153
+ return { order: { ...orderOf(row), refundedAmount, status }, counted: true }
154
+ },
155
+ })
156
+
157
+ /** Mark an order disputed (a chargeback opened): `null` for one the app never recorded. */
158
+ export const disputeOrder = mutation({
159
+ args: { orderId: v.string() },
160
+ returns: v.union(vOrder, v.null()),
161
+ handler: async (ctx, { orderId }) => {
162
+ const row = await orderRow(ctx, orderId)
163
+ if (!row) return null
164
+ await ctx.db.patch('billingCommerceOrders', row._id, { status: 'disputed' })
165
+ return { ...orderOf(row), status: 'disputed' as const }
166
+ },
167
+ })
168
+
169
+ /** The entity's entitlement row, made empty when it has none: a grant needs a row to land on. */
170
+ async function entitlementRow(ctx: MutationCtx, userId: string): Promise<Doc<'billingEntitlements'>> {
171
+ const row = await ctx.db.query('billingEntitlements').withIndex('userId', q => q.eq('userId', userId)).unique()
172
+ if (row) return row
173
+ const id = await ctx.db.insert('billingEntitlements', { userId, activeProductIds: [], benefits: [], meters: [], updatedAt: Date.now() })
174
+ return (await ctx.db.get('billingEntitlements', id))!
175
+ }
176
+
177
+ /**
178
+ * Write an entity's plan, its products and benefits, as the catalog grants
179
+ * them, keeping its meters and reservations as they are: on an adapter
180
+ * provider the balance is the record, never a provider's read, so `upsert`
181
+ * (which takes the meters from the read) is not the call.
182
+ */
183
+ export const setPlanState = mutation({
184
+ args: {
185
+ userId: v.string(),
186
+ customerId: v.optional(v.string()),
187
+ activeProductIds: v.array(v.string()),
188
+ benefits: v.array(vEntitlementBenefit),
189
+ },
190
+ returns: v.null(),
191
+ handler: async (ctx, { userId, customerId, activeProductIds, benefits }) => {
192
+ const row = await entitlementRow(ctx, userId)
193
+ await ctx.db.patch('billingEntitlements', row._id, { ...(customerId === undefined ? {} : { customerId }), activeProductIds, benefits, updatedAt: Date.now() })
194
+ // A plan that changed moves the owner's waiting jobs up a tier, never down.
195
+ await retierOwner(ctx, userId)
196
+ return null
197
+ },
198
+ })
199
+
200
+ type MeterState = Doc<'billingEntitlements'>['meters'][number]
201
+
202
+ /** The fields of `values` that are set. */
203
+ function pick<T extends Record<string, unknown>>(values: T): Partial<T> {
204
+ return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)) as Partial<T>
205
+ }
206
+
207
+ /** How many of a meter's latest plan grants a lapse reads: years of monthly grants. */
208
+ const PLAN_GRANTS_READ = 200
209
+
210
+ /**
211
+ * Close the meter's open plan grants that do not roll over, each with what
212
+ * is left of it, as far as the balance still holds it, but those `keep`
213
+ * names. What the meter consumed is taken once, from the oldest grant open
214
+ * at the time: each stretch between two grants' landings goes to the grants
215
+ * landed by then, oldest first. A grant already closed took what it was
216
+ * spent of before it closed, so the open ones are not charged for it again.
217
+ * Answers how many credits lapsed.
218
+ */
219
+ async function lapsePlanGrants(ctx: MutationCtx, userId: string, meter: MeterState, keep: readonly string[] = []): Promise<number> {
220
+ // The meter's latest plan grants, oldest first, whatever packs landed between them: far more than the months any open grant shares.
221
+ const plans: Array<Doc<'billingCreditGrants'>> = []
222
+ const grants = ctx.db.query('billingCreditGrants').withIndex('userId_meterId', q => q.eq('userId', userId).eq('meterId', meter.meterId)).order('desc')
223
+ for await (const grant of grants) {
224
+ if (grant.source !== 'plan' || grant.rollover) continue
225
+ plans.unshift(grant)
226
+ if (plans.length === PLAN_GRANTS_READ) break
227
+ }
228
+ const left = plans.map(grant => grant.amount - (grant.closed ?? 0))
229
+ plans.forEach((grant, landed) => {
230
+ let stretch = Math.max(0, (plans[landed + 1]?.consumedAtGrant ?? meter.consumedUnits) - grant.consumedAtGrant)
231
+ for (let at = 0; at <= landed && stretch > 0; at++) {
232
+ const taken = Math.min(left[at]!, stretch)
233
+ left[at]! -= taken
234
+ stretch -= taken
235
+ }
236
+ })
237
+ let lapsed = 0
238
+ for (const [at, grant] of plans.entries()) {
239
+ if (grant.closed !== undefined || keep.includes(grant.externalId)) continue
240
+ const closed = Math.min(left[at]!, Math.max(0, meter.balance - lapsed))
241
+ lapsed += closed
242
+ await ctx.db.patch('billingCreditGrants', grant._id, { closed })
243
+ }
244
+ return lapsed
245
+ }
246
+
247
+ /**
248
+ * Grant credits once per `externalId`, on a meter the row may not list yet.
249
+ * A plan's grant (`source: 'plan'`) first lapses what is left of the
250
+ * meter's earlier plan grants that do not roll over: a month's allowance
251
+ * ends where the next begins, and what was spent since it landed came out
252
+ * of it first. `keep` names the grants that stay open: the monthly cycle's
253
+ * other plans' of the same month. Answers whether the grant was new, and
254
+ * the balance.
255
+ */
256
+ export const grantCredits = mutation({
257
+ args: {
258
+ userId: v.string(),
259
+ meterId: v.string(),
260
+ amount: v.number(),
261
+ externalId: v.string(),
262
+ source: v.union(v.literal('plan'), v.literal('pack'), v.literal('grant')),
263
+ rollover: v.boolean(),
264
+ cycleStart: v.optional(v.number()),
265
+ cycleEnd: v.optional(v.number()),
266
+ keep: v.optional(v.array(v.string())),
267
+ orderId: v.optional(v.string()),
268
+ /**
269
+ * A yearly plan's month: the subscription whose order pays for it, and
270
+ * since when that order can have been recorded (its period's start).
271
+ * Read in this same transaction, so a refund or an order landing
272
+ * meanwhile is never missed; a period whose order was taken back whole
273
+ * grants nothing.
274
+ */
275
+ paidBy: v.optional(v.object({ subscriptionId: v.string(), since: v.number() })),
276
+ },
277
+ returns: v.object({ granted: v.boolean(), balance: v.number() }),
278
+ handler: async (ctx, { userId, meterId, amount, externalId, source, rollover, cycleStart, cycleEnd, keep, orderId, paidBy }) => {
279
+ if (!Number.isFinite(amount) || amount <= 0) throw new Error(`[nuxt-backend] commerce.grantCredits: \`amount\` must be a finite number above zero (got ${amount}).`)
280
+ const row = await entitlementRow(ctx, userId)
281
+ const index = row.meters.findIndex(meter => meter.meterId === meterId)
282
+ const meter = index === -1 ? { meterId, consumedUnits: 0, creditedUnits: 0, balance: 0 } : row.meters[index]!
283
+ if (await ctx.db.query('billingCreditGrants').withIndex('externalId', q => q.eq('externalId', externalId)).first()) {
284
+ return { granted: false, balance: meter.balance }
285
+ }
286
+ const paying = paidBy ? await payingOrder(ctx, paidBy) : orderId === undefined ? null : { orderId, status: 'paid' as const }
287
+ if (paying && (paying.status === 'refunded' || paying.status === 'disputed')) return { granted: false, balance: meter.balance }
288
+ const lapsed = source === 'plan' ? await lapsePlanGrants(ctx, userId, meter, keep) : 0
289
+ const now = Date.now()
290
+ await ctx.db.insert('billingCreditGrants', { userId, meterId, externalId, amount, source, rollover, consumedAtGrant: meter.consumedUnits, ...(paying ? { orderId: paying.orderId } : {}), at: now })
291
+ const next = {
292
+ ...meter,
293
+ balance: meter.balance - lapsed + amount,
294
+ creditedUnits: meter.creditedUnits - lapsed + amount,
295
+ ...(source === 'plan' ? { ...pick({ cycleStart, cycleEnd }), rollover } : {}),
296
+ }
297
+ const meters = index === -1 ? [...row.meters, next] : row.meters.map((entry, at) => at === index ? next : entry)
298
+ await ctx.db.patch('billingEntitlements', row._id, { meters, updatedAt: now })
299
+ return { granted: true, balance: next.balance }
300
+ },
301
+ })
302
+
303
+ /**
304
+ * Take a grant back, once: a refunded or disputed order's credits, as many
305
+ * of them as the balance still holds, the meter's open reservations
306
+ * counted in (what was spent stays spent). A reservation held when the
307
+ * grant goes is reclaimed with it: released, it brings the balance back to
308
+ * where the grant left it; settled, the meter stays short by that spend
309
+ * until the next grant. Answers how many left the balance; `0` for a grant
310
+ * never made or already closed.
311
+ */
312
+ export const revokeGrant = mutation({
313
+ args: { userId: v.string(), externalId: v.string() },
314
+ returns: v.number(),
315
+ handler: async (ctx, { userId, externalId }) => {
316
+ const grant = await ctx.db.query('billingCreditGrants').withIndex('externalId', q => q.eq('externalId', externalId)).first()
317
+ return grant && grant.userId === userId ? await revoke(ctx, grant) : 0
318
+ },
319
+ })
320
+
321
+ /**
322
+ * Take back every grant an order paid for, each once as `revokeGrant`
323
+ * takes one: its own, and a yearly plan's months. Answers how many left
324
+ * the balance.
325
+ */
326
+ export const revokeOrderGrants = mutation({
327
+ args: { userId: v.string(), orderId: v.string() },
328
+ returns: v.number(),
329
+ handler: async (ctx, { userId, orderId }) => {
330
+ let taken = 0
331
+ for (const grant of await ctx.db.query('billingCreditGrants').withIndex('userId_orderId', q => q.eq('userId', userId).eq('orderId', orderId)).collect()) {
332
+ taken += await revoke(ctx, grant)
333
+ }
334
+ return taken
335
+ },
336
+ })
337
+
338
+ /**
339
+ * Tie the grants under `externalIds` that no order paid for yet to
340
+ * `orderId`: a yearly plan's months the cycle granted before the order
341
+ * that pays for them arrived, granted between `from` and `until` (its
342
+ * period) where they are given.
343
+ */
344
+ export const linkGrants = mutation({
345
+ args: { userId: v.string(), orderId: v.string(), externalIds: v.array(v.string()), from: v.optional(v.number()), until: v.optional(v.number()) },
346
+ returns: v.null(),
347
+ handler: async (ctx, { userId, orderId, externalIds, from = -Infinity, until = Infinity }) => {
348
+ for (const externalId of externalIds) {
349
+ const grant = await ctx.db.query('billingCreditGrants').withIndex('externalId', q => q.eq('externalId', externalId)).first()
350
+ if (grant && grant.userId === userId && grant.orderId === undefined && grant.at >= from && grant.at <= until) await ctx.db.patch('billingCreditGrants', grant._id, { orderId })
351
+ }
352
+ return null
353
+ },
354
+ })
355
+
356
+ /** The latest order of a subscription recorded since `since`: the one paying for its period, `null` before it arrives. */
357
+ function payingOrder(ctx: { db: QueryCtx['db'] }, { subscriptionId, since }: { subscriptionId: string, since: number }) {
358
+ return ctx.db.query('billingCommerceOrders').withIndex('subscriptionId_createdAt', q => q.eq('subscriptionId', subscriptionId).gte('createdAt', since)).order('desc').first()
359
+ }
360
+
361
+ /** Close one grant, as many of its credits as the balance still holds: `0` for one already closed. */
362
+ async function revoke(ctx: MutationCtx, grant: Doc<'billingCreditGrants'>): Promise<number> {
363
+ if (grant.closed !== undefined) return 0
364
+ const row = await ctx.db.query('billingEntitlements').withIndex('userId', q => q.eq('userId', grant.userId)).unique()
365
+ const index = row ? row.meters.findIndex(meter => meter.meterId === grant.meterId) : -1
366
+ const meter = index === -1 ? undefined : row!.meters[index]!
367
+ const held = activePendings(row?.pendingSpends, Date.now()).filter(entry => entry.meterId === grant.meterId).reduce((sum, entry) => sum + entry.amount, 0)
368
+ // Of what open reservations hold, only as much as this grant still has unspent: settled spends since it landed came out of it first.
369
+ const settledSince = Math.max(0, (meter?.consumedUnits ?? 0) - held - grant.consumedAtGrant)
370
+ const heldOfIt = Math.min(held, Math.max(0, grant.amount - settledSince))
371
+ const taken = meter ? Math.min(grant.amount, Math.max(0, meter.balance + heldOfIt)) : 0
372
+ await ctx.db.patch('billingCreditGrants', grant._id, { closed: taken })
373
+ if (meter && taken > 0) {
374
+ const meters = row!.meters.map((entry, at) => at === index ? { ...entry, balance: entry.balance - taken, creditedUnits: entry.creditedUnits - taken } : entry)
375
+ await ctx.db.patch('billingEntitlements', row!._id, { meters, updatedAt: Date.now() })
376
+ }
377
+ return taken
378
+ }
379
+
380
+ /** Whether a grant was made under `externalId`. */
381
+ export const hasGrant = query({
382
+ args: { externalId: v.string() },
383
+ returns: v.boolean(),
384
+ handler: async (ctx, { externalId }) =>
385
+ (await ctx.db.query('billingCreditGrants').withIndex('externalId', q => q.eq('externalId', externalId)).first()) !== null,
386
+ })
387
+
388
+ /**
389
+ * Forget a billing entity's records here (an account's erasure): its
390
+ * customers, orders and grants. The provider, the merchant of record,
391
+ * keeps what tax law has it keep.
392
+ */
393
+ export const forgetEntity = mutation({
394
+ args: { entityId: v.string() },
395
+ returns: v.null(),
396
+ handler: async (ctx, { entityId }) => {
397
+ for await (const row of ctx.db.query('billingCommerceCustomers').withIndex('entityId_provider', q => q.eq('entityId', entityId))) {
398
+ await ctx.db.delete('billingCommerceCustomers', row._id)
399
+ }
400
+ for await (const row of ctx.db.query('billingCommerceOrders').withIndex('entityId_createdAt', q => q.eq('entityId', entityId))) {
401
+ await ctx.db.delete('billingCommerceOrders', row._id)
402
+ }
403
+ for await (const row of ctx.db.query('billingCreditGrants').withIndex('userId_meterId', q => q.eq('userId', entityId))) {
404
+ await ctx.db.delete('billingCreditGrants', row._id)
405
+ }
406
+ return null
407
+ },
408
+ })