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
@@ -0,0 +1,487 @@
1
+ import { type FunctionReference, makeFunctionReference } from 'convex/server'
2
+ import { planCreditUnits } from '../../catalog.js'
3
+ import { START_FREE_PLAN_FUNCTION } from '../../constants.js'
4
+ import { logBackend } from '../../log.js'
5
+ import { handleWebhookDelivery, parseSecretList } from '../webhook-guard.js'
6
+ import { createCommerceWebhookHandler } from './commerce-webhooks.js'
7
+ import { type CatalogProduct, catalogProductOf } from './commerce.js'
8
+ import type { BillingContext } from './context.js'
9
+ import type { BillingCustomers } from './customers.js'
10
+ import type { BillingEntitlements } from './entitlements.js'
11
+ import type { BillingFreePlan, FreePlanStart, QueueCtx } from './free-plan.js'
12
+ import type { NeutralBillingEvent, NeutralOrder, NeutralSubscription } from './providers/types.js'
13
+ import type { ProviderCtx, RunWriteCtx } from './types/base.js'
14
+
15
+ // What adapter mode (commerce.ts) does with a provider's verified, neutral
16
+ // event: the subscription into the provider component's subscriptions
17
+ // table, the paid order into the order ledger with its credits granted,
18
+ // a refund or a dispute taking the credits back; then the entity's plan is
19
+ // written to the cache again. And the credit cycle the provider does not
20
+ // run: the free plan's monthly allowance (and a yearly plan's on a monthly
21
+ // meter cycle), granted a month at a time on the scheduler.
22
+
23
+ /** A subscription row as the provider component keeps it. */
24
+ interface SubscriptionRow {
25
+ id: string
26
+ customerId: string
27
+ createdAt: string
28
+ modifiedAt: string | null
29
+ amount: number | null
30
+ currency: string | null
31
+ recurringInterval: string | null
32
+ status: string
33
+ currentPeriodStart: string
34
+ currentPeriodEnd: string | null
35
+ cancelAtPeriodEnd: boolean
36
+ startedAt: string | null
37
+ endedAt: string | null
38
+ productId: string
39
+ checkoutId: string | null
40
+ metadata: Record<string, unknown>
41
+ canceledAt?: string | null
42
+ endsAt?: string | null
43
+ trialStart?: string | null
44
+ trialEnd?: string | null
45
+ }
46
+
47
+ /** Statuses of a subscription the entity still holds. */
48
+ const LIVE_STATUSES = new Set(['active', 'trialing', 'past_due', 'paused'])
49
+
50
+ /** The month a cycle grant belongs to, `YYYY-MM` in UTC. */
51
+ function monthOf(at: number): string {
52
+ return new Date(at).toISOString().slice(0, 7)
53
+ }
54
+
55
+ /** A day in ms. */
56
+ const DAY_MS = 24 * 60 * 60 * 1000
57
+
58
+ /** The first moment of the next UTC month: when the next cycle grant runs. */
59
+ function nextMonth(at: number): number {
60
+ const date = new Date(at)
61
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1)
62
+ }
63
+
64
+ /** An ISO time of epoch ms, or `null`. */
65
+ function isoOf(at: number | null | undefined): string | null {
66
+ return typeof at === 'number' && Number.isFinite(at) ? new Date(at).toISOString() : null
67
+ }
68
+
69
+ /** Epoch ms of an ISO time, or `undefined`. */
70
+ function msOf(at: string | null | undefined): number | undefined {
71
+ const ms = at ? Date.parse(at) : Number.NaN
72
+ return Number.isFinite(ms) ? ms : undefined
73
+ }
74
+
75
+ /** A row's state fields: its status, its period, and when it was canceled, ends, ended or trials. */
76
+ type StateFields = Pick<SubscriptionRow, 'status' | 'currentPeriodStart' | 'currentPeriodEnd' | 'cancelAtPeriodEnd' | 'endedAt' | 'canceledAt' | 'endsAt' | 'trialStart' | 'trialEnd'>
77
+
78
+ /** The period a delivered subscription is in: a later end than the row's starts the next one there. */
79
+ function periodOf(subscription: NeutralSubscription, prior: Partial<SubscriptionRow>, now: string): Pick<SubscriptionRow, 'currentPeriodStart' | 'currentPeriodEnd'> {
80
+ const currentPeriodEnd = isoOf(subscription.currentPeriodEnd) ?? prior.currentPeriodEnd ?? null
81
+ const renewed = prior.currentPeriodEnd != null && currentPeriodEnd !== null && Date.parse(currentPeriodEnd) > Date.parse(prior.currentPeriodEnd)
82
+ return { currentPeriodStart: renewed ? prior.currentPeriodEnd! : prior.currentPeriodStart ?? now, currentPeriodEnd }
83
+ }
84
+
85
+ /** The state a delivered subscription sets on its row, keeping each time from `prior` where it was set before: an ended one stays ended. */
86
+ function stateFields(subscription: NeutralSubscription, prior: Partial<SubscriptionRow>, now: string): StateFields {
87
+ const period = periodOf(subscription, prior, now)
88
+ const trial = { trialStart: prior.trialStart ?? null, trialEnd: prior.trialEnd ?? null }
89
+ if (subscription.status === 'ended' || prior.endedAt != null) {
90
+ return { status: 'canceled', ...period, cancelAtPeriodEnd: false, endedAt: prior.endedAt ?? now, canceledAt: prior.canceledAt ?? now, endsAt: prior.endsAt ?? now, ...trial }
91
+ }
92
+ const cancelling = subscription.cancelAtPeriodEnd
93
+ return {
94
+ status: subscription.status,
95
+ ...period,
96
+ cancelAtPeriodEnd: cancelling,
97
+ endedAt: null,
98
+ canceledAt: cancelling ? prior.canceledAt ?? now : null,
99
+ endsAt: cancelling ? period.currentPeriodEnd : null,
100
+ ...(subscription.status === 'trialing' ? { trialStart: trial.trialStart ?? now, trialEnd: period.currentPeriodEnd } : trial),
101
+ }
102
+ }
103
+
104
+ /** Whether a product is a yearly plan whose credits come a month at a time. */
105
+ function monthlyCycleOf(product: CatalogProduct): boolean {
106
+ return product?.kind === 'plan' && product.interval === 'year' && product.plan.meterCycle === 'month' && !!product.plan.credits && !product.plan.credits.once
107
+ }
108
+
109
+ /** The months from `from` through `to`, `YYYY-MM` in UTC, at most 13: the cycle grants a year's order can have made. */
110
+ function monthsBetween(from: number, to: number): string[] {
111
+ const months: string[] = []
112
+ for (let at = from; at <= to && months.length < 13; at = nextMonth(at)) months.push(monthOf(at))
113
+ return months
114
+ }
115
+
116
+ /** A grant's cycle, from the period its subscription row is in: each bound where the row has it. */
117
+ function periodBounds(subscription: Pick<SubscriptionRow, 'currentPeriodStart' | 'currentPeriodEnd'> | null): { cycleStart?: number, cycleEnd?: number } {
118
+ const cycleStart = msOf(subscription?.currentPeriodStart)
119
+ const cycleEnd = msOf(subscription?.currentPeriodEnd)
120
+ return { ...(cycleStart === undefined ? {} : { cycleStart }), ...(cycleEnd === undefined ? {} : { cycleEnd }) }
121
+ }
122
+
123
+ /**
124
+ * Where the period an order pays for starts: its subscription's period
125
+ * start while that period holds the order, else a day before the order.
126
+ * The subscription's own delivery can start the cycle first, so its first
127
+ * month can be the one before the order's.
128
+ */
129
+ function periodStartOf(subscription: Pick<SubscriptionRow, 'currentPeriodStart'> | null, orderedAt: number): number {
130
+ const start = msOf(subscription?.currentPeriodStart)
131
+ return start !== undefined && start <= orderedAt ? start : orderedAt - DAY_MS
132
+ }
133
+
134
+ /** Whether a recorded order was taken back whole: refunded in full or disputed. */
135
+ function reversed(order: { status: string }): boolean {
136
+ return order.status === 'refunded' || order.status === 'disputed'
137
+ }
138
+
139
+ /** The provider component's subscription read, which the structural refs leave out. */
140
+ type GetSubscription = FunctionReference<'query', 'internal', { id: string }, SubscriptionRow | null>
141
+
142
+ /** The events, the credit cycle and the webhook edge of adapter mode. */
143
+ export function createCommerceEvents(
144
+ context: BillingContext,
145
+ { refreshEntitlements }: Pick<BillingEntitlements, 'refreshEntitlements'>,
146
+ { recordTrial }: Pick<BillingCustomers, 'recordTrial'>,
147
+ freePlan: Pick<BillingFreePlan, 'restartAfterRevoke'>,
148
+ ) {
149
+ const { provider, providerLib, components, webhookLog, webhookSecret, recordEvent, entityDeleting, cache } = context
150
+ const commerce = context.commerce!
151
+ const { refs, name, config: { definition } } = commerce
152
+ /** The merchant of record, as the log names it. */
153
+ const merchant = name
154
+ const getSubscription = (components.polar as unknown as { lib: { getSubscription: GetSubscription } }).lib.getSubscription
155
+ // The scaffold's `startFreePlan`, which runs the cycle for `{ entityId }`.
156
+ const cycleReference = makeFunctionReference<'action', { entityId?: string }>(START_FREE_PLAN_FUNCTION)
157
+
158
+ /** The product an id sells, by the ids in force. */
159
+ const productOf = (productId: string | null | undefined): CatalogProduct => catalogProductOf(definition, commerce.ids, productId)
160
+
161
+ /**
162
+ * The entity an event is for: the one the checkout named in its metadata,
163
+ * else the one the customer was linked to, else the one its subscription
164
+ * was synced for (the subscription row's customer is the entity).
165
+ */
166
+ const entityOf = async (ctx: RunWriteCtx, ids: { entityId: string | null, customerId: string | null, subscriptionId?: string | null }): Promise<string | null> => {
167
+ if (ids.entityId) return ids.entityId
168
+ if (ids.customerId) {
169
+ const linked = await ctx.runQuery(refs.entityOfCustomer, { provider: name, customerId: ids.customerId })
170
+ if (linked) return linked
171
+ }
172
+ return ids.subscriptionId ? (await ctx.runQuery(getSubscription, { id: ids.subscriptionId }))?.customerId ?? null : null
173
+ }
174
+
175
+ /** Note who the entity is at the provider, and map it in the provider component, whose rows read by it. */
176
+ const linkEntity = async (ctx: RunWriteCtx, entityId: string, customerId: string | null): Promise<void> => {
177
+ if (customerId) await ctx.runMutation(refs.linkCustomer, { entityId, provider: name, customerId })
178
+ await ctx.runMutation(providerLib.insertCustomer, { id: entityId, userId: entityId })
179
+ }
180
+
181
+ /** The plan's price at its interval, in the catalog's currency. */
182
+ const priceOf = (product: CatalogProduct): { amount: number, currency: string } | null => {
183
+ if (product?.kind !== 'plan') return null
184
+ const prices = product.plan.prices as Record<string, unknown>
185
+ const own = prices[product.interval]
186
+ if (typeof own === 'number') return { amount: own, currency: definition.currency?.toLowerCase() ?? 'usd' }
187
+ const [currency, amounts] = Object.entries(prices)[0] ?? []
188
+ const amount = (amounts as Record<string, unknown> | undefined)?.[product.interval]
189
+ return currency && typeof amount === 'number' ? { amount, currency: currency.toLowerCase() } : null
190
+ }
191
+
192
+ /** The row a delivered subscription becomes, from what the table held: an ended one stays ended. */
193
+ const subscriptionRow = (subscription: NeutralSubscription, entityId: string, existing: SubscriptionRow | null): SubscriptionRow => {
194
+ const now = new Date().toISOString()
195
+ const prior: Partial<SubscriptionRow> = existing ?? {}
196
+ const productId = subscription.productId ?? prior.productId ?? ''
197
+ const product = productOf(productId)
198
+ const price = priceOf(product)
199
+ return {
200
+ id: subscription.id,
201
+ customerId: entityId,
202
+ createdAt: prior.createdAt ?? now,
203
+ modifiedAt: now,
204
+ amount: price?.amount ?? prior.amount ?? null,
205
+ currency: price?.currency ?? prior.currency ?? null,
206
+ recurringInterval: product?.kind === 'plan' ? product.interval : prior.recurringInterval ?? null,
207
+ startedAt: prior.startedAt ?? now,
208
+ productId,
209
+ checkoutId: prior.checkoutId ?? null,
210
+ metadata: subscription.metadata,
211
+ ...stateFields(subscription, prior, now),
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Keep a plan change scheduled for the next period past a delivery of its
217
+ * subscription, which no adapter's delivery names: recorded again at the
218
+ * row's new time while it is still to come and the row still on the old
219
+ * product, dropped once the row moved to it.
220
+ */
221
+ const keepScheduledChange = async (ctx: RunWriteCtx, entityId: string, row: SubscriptionRow): Promise<void> => {
222
+ const [change] = await ctx.runQuery(cache.subscriptionChanges, { subscriptionIds: [row.id] })
223
+ const pending = change?.pendingChange
224
+ if (!pending) return
225
+ const kept = pending.appliesAt > Date.now() && pending.productId !== row.productId && !row.endedAt
226
+ await ctx.runMutation(cache.recordSubscriptionChange, { subscriptionId: row.id, userId: entityId, pendingChange: kept ? pending : null, resumesAt: change.resumesAt, modifiedAt: Date.parse(row.modifiedAt ?? '') || Date.now() })
227
+ }
228
+
229
+ const onSubscription = async (ctx: RunWriteCtx, subscription: NeutralSubscription): Promise<void> => {
230
+ const entityId = await entityOf(ctx, { ...subscription, subscriptionId: subscription.id })
231
+ if (!entityId) {
232
+ logBackend('warn', 'billing.commerce_unknown_entity', `A ${merchant} subscription delivery named no billing entity the app knows; it was acknowledged and left out.`)
233
+ return
234
+ }
235
+ if (await entityDeleting(ctx, entityId)) return
236
+ await linkEntity(ctx, entityId, subscription.customerId)
237
+ const existing = await ctx.runQuery(getSubscription, { id: subscription.id })
238
+ const row = subscriptionRow(subscription, entityId, existing)
239
+ await ctx.runMutation(providerLib.updateSubscription, { subscription: row as unknown as Record<string, unknown> })
240
+ await keepScheduledChange(ctx, entityId, row)
241
+ if (row.trialStart && !existing?.trialStart) await recordTrial(ctx, entityId)
242
+ await refreshEntitlements(ctx, entityId)
243
+ // The month's grant goes by its key, so this and the order's start grant it once.
244
+ if (!row.endedAt && LIVE_STATUSES.has(row.status) && monthlyCycleOf(productOf(row.productId))) await (ctx as QueueCtx).scheduler.runAfter(0, cycleReference, { entityId })
245
+ if (row.endedAt && !existing?.endedAt) {
246
+ // Back on the free plan, which starts its credit cycle again.
247
+ await freePlan.restartAfterRevoke(ctx as QueueCtx, entityId, { id: row.id, customerDeleted: false })
248
+ }
249
+ await recordEvent(ctx, entityId, { type: 'billing.subscription_updated', actor: null, targetId: row.id, data: { productId: row.productId, status: row.status } })
250
+ }
251
+
252
+ /** The subscription row an order renews, if it renews one. */
253
+ const subscriptionOf = async (ctx: RunWriteCtx, subscriptionId: string | null): Promise<SubscriptionRow | null> =>
254
+ subscriptionId ? await ctx.runQuery(getSubscription, { id: subscriptionId }) : null
255
+
256
+ /**
257
+ * Grant what a paid order buys, under the order's key: a pack's credits,
258
+ * which keep; a plan's for its period, which lapse at the next unless the
259
+ * catalog rolls them over. A yearly plan on a monthly meter cycle starts
260
+ * the monthly cycle instead, once its subscription is synced: before
261
+ * that, the subscription's own delivery starts it.
262
+ */
263
+ const grantOrder = async (ctx: RunWriteCtx, entityId: string, order: NeutralOrder, product: CatalogProduct, orderedAt: number): Promise<void> => {
264
+ if (product?.kind === 'pack') {
265
+ const pack = definition.packs![product.key]!
266
+ await ctx.runMutation(refs.grantCredits, { userId: entityId, meterId: pack.credits.meter, amount: pack.credits.units, externalId: `order:${order.id}`, source: 'pack', rollover: pack.credits.rollover ?? true, orderId: order.id })
267
+ return
268
+ }
269
+ const credits = product?.kind === 'plan' ? product.plan.credits : undefined
270
+ if (product?.kind !== 'plan' || !credits || credits.once) return
271
+ const subscription = await subscriptionOf(ctx, order.subscriptionId)
272
+ if (monthlyCycleOf(product)) {
273
+ await linkMonths(ctx, entityId, order.id, product.key, subscription, orderedAt)
274
+ if (subscription && subscription.endedAt == null) await (ctx as QueueCtx).scheduler.runAfter(0, cycleReference, { entityId })
275
+ return
276
+ }
277
+ const units = planCreditUnits(credits, product.interval)
278
+ if (units) await ctx.runMutation(refs.grantCredits, { userId: entityId, meterId: credits.meter, amount: units, externalId: `order:${order.id}`, source: 'plan', rollover: credits.rollover ?? false, orderId: order.id, ...periodBounds(subscription) })
279
+ }
280
+
281
+ /**
282
+ * The months of an order's period the cycle granted before the order
283
+ * arrived, tied to it to take back: from when it was recorded, never past
284
+ * a later period's start (a redelivered year-old order). A month's key is
285
+ * shared by the periods on either side of a renewal, so the grant's own
286
+ * time decides.
287
+ */
288
+ const linkMonths = async (ctx: RunWriteCtx, entityId: string, orderId: string, planKey: string, subscription: SubscriptionRow | null, orderedAt: number): Promise<void> => {
289
+ const periodStart = msOf(subscription?.currentPeriodStart)
290
+ const until = periodStart !== undefined && periodStart > orderedAt ? periodStart - 1 : undefined
291
+ const from = periodStartOf(subscription, orderedAt)
292
+ const externalIds = monthsBetween(from, until ?? Date.now()).map(month => `cycle:${entityId}:${planKey}:${month}`)
293
+ await ctx.runMutation(refs.linkGrants, { userId: entityId, orderId, externalIds, from, ...(until === undefined ? {} : { until }) })
294
+ }
295
+
296
+ /** A subscription's order that arrived before the subscription it renews: failed, the provider delivers it again. */
297
+ const beforeItsSubscription = () => new Error(`[nuxt-backend] A ${merchant} order arrived before its subscription; the provider delivers it again.`)
298
+
299
+ const onOrderPaid = async (ctx: RunWriteCtx, order: NeutralOrder): Promise<void> => {
300
+ const entityId = await entityOf(ctx, order)
301
+ // An order that names only its subscription waits for that subscription's own delivery.
302
+ if (!entityId && order.subscriptionId && !await subscriptionOf(ctx, order.subscriptionId)) throw beforeItsSubscription()
303
+ if (!entityId) {
304
+ logBackend('warn', 'billing.commerce_unknown_entity', `A ${merchant} order named no billing entity the app knows; it was acknowledged and left out.`)
305
+ return
306
+ }
307
+ if (await entityDeleting(ctx, entityId)) return
308
+ await linkEntity(ctx, entityId, order.customerId)
309
+ const productId = order.productId ?? (await subscriptionOf(ctx, order.subscriptionId))?.productId ?? null
310
+ // A subscription's order that names no product waits for the subscription's own delivery too.
311
+ if (!productId && order.subscriptionId) throw beforeItsSubscription()
312
+ const recorded = await ctx.runMutation(refs.recordOrder, {
313
+ orderId: order.id,
314
+ provider: name,
315
+ entityId,
316
+ ...(productId ? { productId } : {}),
317
+ ...(order.subscriptionId ? { subscriptionId: order.subscriptionId } : {}),
318
+ amount: order.amount,
319
+ ...(order.taxAmount === null ? {} : { taxAmount: order.taxAmount }),
320
+ currency: order.currency,
321
+ })
322
+ // A redelivered order grants again what an earlier attempt may not have: each grant lands once by its key.
323
+ const product = productOf(productId)
324
+ const stored = await ctx.runQuery(refs.getOrder, { orderId: order.id })
325
+ await grantOrder(ctx, entityId, order, product, stored?.createdAt ?? Date.now())
326
+ await settleRecorded(ctx, entityId, order, product, recorded, stored)
327
+ }
328
+
329
+ /**
330
+ * The rest of a paid order's delivery once its grants landed and its
331
+ * months were linked: a refund or a dispute that came before it (applied
332
+ * as it was recorded) or while they landed takes them back at once, the
333
+ * order read again for it; then the plan is written again, and a first
334
+ * delivery goes on the activity trail.
335
+ */
336
+ const settleRecorded = async (ctx: RunWriteCtx, entityId: string, order: NeutralOrder, product: CatalogProduct, recorded: boolean, stored: { refundedAmount: number } | null): Promise<void> => {
337
+ const now = await ctx.runQuery(refs.getOrder, { orderId: order.id })
338
+ if (now && reversed(now)) await takeBack(ctx, now)
339
+ await refreshEntitlements(ctx, entityId)
340
+ if (!recorded) return
341
+ await recordEvent(ctx, entityId, { type: 'billing.order_paid', actor: null, targetId: order.id, data: { amount: order.amount, currency: order.currency, ...(product?.kind === 'plan' ? { interval: product.interval } : {}) } })
342
+ if (stored?.refundedAmount) await recordEvent(ctx, entityId, { type: 'billing.order_refunded', actor: null, targetId: order.id, data: { amount: stored.refundedAmount, currency: order.currency } })
343
+ }
344
+
345
+ /**
346
+ * A refunded or disputed order's credits taken back, as many as the
347
+ * balance still holds: every grant it paid for, its own and a yearly
348
+ * plan's months on a monthly cycle. Each closes once, so a second attempt
349
+ * takes nothing twice.
350
+ */
351
+ const takeBack = async (ctx: RunWriteCtx, order: { entityId: string, orderId: string }): Promise<void> => {
352
+ await ctx.runMutation(refs.revokeOrderGrants, { userId: order.entityId, orderId: order.orderId })
353
+ }
354
+
355
+ /**
356
+ * Whether a refund or a dispute moves its order now: not while the
357
+ * order's entity is being erased, nor before the order is recorded, when
358
+ * it is held for the order to apply as it lands.
359
+ */
360
+ const movesNow = async (ctx: RunWriteCtx, orderId: string, reversal: { kind: 'refund' | 'dispute', refundId?: string, amount?: number }): Promise<boolean> => {
361
+ const order = await ctx.runQuery(refs.getOrder, { orderId })
362
+ if (order) return !await entityDeleting(ctx, order.entityId)
363
+ return !await ctx.runMutation(refs.holdReversal, { orderId, ...reversal })
364
+ }
365
+
366
+ const onRefund = async (ctx: RunWriteCtx, event: Extract<NeutralBillingEvent, { type: 'order.refunded' }>): Promise<void> => {
367
+ const { refund } = event
368
+ // A refund pending or failed moves nothing: its `succeeded` delivery does.
369
+ if (refund.status !== 'succeeded' || !refund.orderId) return
370
+ if (!await movesNow(ctx, refund.orderId, { kind: 'refund', refundId: refund.id, ...(refund.amount === null ? {} : { amount: refund.amount }) })) return
371
+ const counted = await ctx.runMutation(refs.refundOrder, { orderId: refund.orderId, refundId: refund.id, ...(refund.amount === null ? {} : { amount: refund.amount }) })
372
+ if (!counted) return
373
+ const { order } = counted
374
+ // A whole refund takes the order's credits back; a partial one keeps them. A redelivery finishes a take-back that failed.
375
+ if (order.status === 'refunded') await takeBack(ctx, order)
376
+ await refreshEntitlements(ctx, order.entityId)
377
+ if (counted.counted) await recordEvent(ctx, order.entityId, { type: 'billing.order_refunded', actor: null, targetId: order.orderId, data: { amount: refund.amount ?? order.amount, currency: refund.currency ?? order.currency } })
378
+ }
379
+
380
+ const onDispute = async (ctx: RunWriteCtx, orderId: string | null): Promise<void> => {
381
+ if (!orderId || !await movesNow(ctx, orderId, { kind: 'dispute' })) return
382
+ const order = await ctx.runMutation(refs.disputeOrder, { orderId })
383
+ if (!order) return
384
+ await takeBack(ctx, order)
385
+ await refreshEntitlements(ctx, order.entityId)
386
+ }
387
+
388
+ /** What the package does with a verified event, then the app's own `commerce.onEvent`. */
389
+ const onEvent = async (ctx: RunWriteCtx, event: NeutralBillingEvent, delivery: { id: string }): Promise<void> => {
390
+ if (event.type === 'subscription.updated') await onSubscription(ctx, event.subscription)
391
+ else if (event.type === 'order.paid') await onOrderPaid(ctx, event.order)
392
+ else if (event.type === 'order.refunded') await onRefund(ctx, event)
393
+ else if (event.type === 'order.disputed') await onDispute(ctx, event.orderId)
394
+ if (commerce.config.onEvent) await commerce.config.onEvent(ctx, event, delivery)
395
+ }
396
+
397
+ /** The entity's live subscriptions. */
398
+ const liveSubscriptions = async (ctx: RunWriteCtx, entityId: string): Promise<SubscriptionRow[]> => {
399
+ const all = await provider.listAllUserSubscriptions(ctx as unknown as ProviderCtx, { userId: entityId }) as SubscriptionRow[]
400
+ return all.filter(subscription => subscription.endedAt == null && LIVE_STATUSES.has(subscription.status))
401
+ }
402
+
403
+ /** The month of credits one plan grants, with its key; `null` for none. */
404
+ const monthOfPlan = (product: CatalogProduct) => {
405
+ const credits = product?.kind === 'plan' ? product.plan.credits : undefined
406
+ const units = credits && !credits.once ? planCreditUnits(credits, 'month') : 0
407
+ return units && product ? { key: product.key, meter: credits!.meter, units, rollover: credits!.rollover ?? false } : null
408
+ }
409
+
410
+ /**
411
+ * The plan credits a month of the cycle grants the entity, one per plan
412
+ * by its key: each live yearly plan's on a monthly meter cycle, or the
413
+ * free plan's while it holds no subscription. The provider's invoices
414
+ * grant the rest.
415
+ */
416
+ const monthlyCredits = async (ctx: RunWriteCtx, entityId: string): Promise<Array<NonNullable<ReturnType<typeof monthOfPlan>> & { paidBy?: { subscriptionId: string, since: number } }>> => {
417
+ const live = await liveSubscriptions(ctx, entityId)
418
+ if (live.length === 0) {
419
+ const free = context.catalogIds?.free ? monthOfPlan(productOf(context.freePlan?.productId)) : null
420
+ return free ? [free] : []
421
+ }
422
+ return live.filter(subscription => monthlyCycleOf(productOf(subscription.productId))).flatMap((subscription) => {
423
+ const month = monthOfPlan(productOf(subscription.productId))
424
+ // Paid for by the subscription's order of this period, which the grant reads as it lands.
425
+ return month ? [{ ...month, paidBy: { subscriptionId: subscription.id, since: periodStartOf(subscription, Date.now()) - DAY_MS } }] : []
426
+ })
427
+ }
428
+
429
+ /**
430
+ * One month of the credit cycle the provider does not run, for one
431
+ * entity: the free plan's allowance while it holds no subscription, a
432
+ * yearly plan's monthly one on a monthly meter cycle, once per month by
433
+ * its key. The next month is scheduled before the grants, so a run that
434
+ * stops between them still has a successor; a run that grants nothing
435
+ * new (a second chain for the same entity meets the same keys) takes its
436
+ * successor back. Answers what the free plan's start answers: `started`
437
+ * the first time, else `subscribed`.
438
+ */
439
+ const cycle = async (ctx: RunWriteCtx, entityId: string, first: () => Promise<void>): Promise<FreePlanStart> => {
440
+ const isNew = (await ctx.runQuery(context.cache.getByUser, { userId: entityId })) === null
441
+ await refreshEntitlements(ctx, entityId)
442
+ if (isNew) await first()
443
+ const months = await monthlyCredits(ctx, entityId)
444
+ if (months.length > 0) {
445
+ const now = Date.now()
446
+ const { scheduler } = ctx as QueueCtx
447
+ const successor = await scheduler.runAt(nextMonth(now), cycleReference, { entityId })
448
+ const cycleStart = Date.UTC(new Date(now).getUTCFullYear(), new Date(now).getUTCMonth(), 1)
449
+ const keyOf = (month: { key: string }) => `cycle:${entityId}:${month.key}:${monthOf(now)}`
450
+ let granted = false
451
+ for (const month of months) {
452
+ const grant = await ctx.runMutation(refs.grantCredits, {
453
+ userId: entityId,
454
+ meterId: month.meter,
455
+ amount: month.units,
456
+ externalId: keyOf(month),
457
+ source: 'plan',
458
+ rollover: month.rollover,
459
+ cycleStart,
460
+ cycleEnd: nextMonth(now),
461
+ // Each plan's month lapses the months before it, never another live plan's of this one.
462
+ keep: months.map(keyOf),
463
+ ...(month.paidBy ? { paidBy: month.paidBy } : {}),
464
+ })
465
+ granted ||= grant.granted
466
+ }
467
+ if (!granted) await scheduler.cancel(successor)
468
+ }
469
+ return isNew ? 'started' : 'subscribed'
470
+ }
471
+
472
+ const webhookSecrets = parseSecretList(webhookSecret)
473
+
474
+ /**
475
+ * `/billing/events` on an adapter provider: its verifier and its neutral
476
+ * events behind the guarded edge. Without an API key the adapter can't be
477
+ * built, and the delivery is answered 503 so the provider sends it again.
478
+ */
479
+ const webhookHandler = async (ctx: RunWriteCtx, request: Request): Promise<Response> => {
480
+ if (!context.accessToken) {
481
+ return handleWebhookDelivery(ctx, webhookLog, { service: 'billing', deliveryId: null, request, secretsConfigured: false, verify: async () => ({ outcome: 'invalid_signature' }) })
482
+ }
483
+ return createCommerceWebhookHandler<RunWriteCtx>({ provider: commerce.client(), secrets: webhookSecrets, webhookLog, onEvent })(ctx, request)
484
+ }
485
+
486
+ return { onEvent, cycle, webhookHandler }
487
+ }
@@ -0,0 +1,110 @@
1
+ import { backendError } from '../../errors.js'
2
+ import { commerceCall, polarOnly } from './commerce.js'
3
+ import { ADMIN_WRITE, BILLING_ACCESS, type BillingContext, resolveLimit } from './context.js'
4
+ import type { BillingOrder } from './types/options.js'
5
+ import type { Billing } from './types/surface.js'
6
+
7
+ // The order history, the invoices and the refunds of adapter mode
8
+ // (commerce.ts): the orders from the app's ledger, which the provider's
9
+ // paid-order deliveries fill, and the invoice and the refund through the
10
+ // adapter. The provider, the merchant of record, issues the invoice and
11
+ // keeps the tax; usage history is Polar's (its events API) for now.
12
+
13
+ /** A ledger order as `getOrders` lists one, in the shape `<BillingHistory>` reads. */
14
+ function orderOf(order: { orderId: string, createdAt: number, status: string, amount: number, currency: string, productId?: string, subscriptionId?: string, taxAmount?: number, refundedAmount: number }): BillingOrder {
15
+ return {
16
+ id: order.orderId,
17
+ createdAt: new Date(order.createdAt).toISOString(),
18
+ status: order.status,
19
+ totalAmount: order.amount,
20
+ currency: order.currency,
21
+ paid: true,
22
+ // The provider numbers its invoices; the ledger keeps none.
23
+ invoiceNumber: null,
24
+ isInvoiceGenerated: true,
25
+ refundedAmount: order.refundedAmount,
26
+ ...(order.taxAmount === undefined ? {} : { taxAmount: order.taxAmount }),
27
+ productId: order.productId ?? null,
28
+ subscriptionId: order.subscriptionId ?? null,
29
+ }
30
+ }
31
+
32
+ /** The history of one `setupBilling` call in adapter mode, in the shape {@link createHistory} returns. */
33
+ export function createCommerceHistory({ commerce, accessToken, requireEntity, requireAdmin, requireProviderAccess, throttle, recordEvent }: BillingContext) {
34
+ const mode = commerce!
35
+
36
+ const getOrders: Billing['getOrders'] = async (ctx, options = {}) => {
37
+ const { userId } = await requireEntity(ctx, BILLING_ACCESS.records)
38
+ if (!accessToken) return null
39
+ await throttle(ctx, userId, 'order reads')
40
+ // The ledger pages by its own cursor, opaque at the boundary like the provider's page number.
41
+ const read = await ctx.runQuery(mode.refs.listOrders, { entityId: userId, paginationOpts: { cursor: options.cursor ?? null, numItems: resolveLimit(options.limit) } })
42
+ const items = read.page.map(orderOf)
43
+ return {
44
+ items,
45
+ // The ledger counts no total: what this page holds, and one more page while there is one.
46
+ pagination: { totalCount: items.length, maxPage: read.isDone ? 1 : 2 },
47
+ ...(read.isDone ? {} : { nextCursor: read.continueCursor }),
48
+ }
49
+ }
50
+
51
+ /** The order, when it is the entity's own; refused like someone else's when it is not there. */
52
+ const ownOrder = async (ctx: Parameters<Billing['getInvoiceUrl']>[0], userId: string, orderId: string) => {
53
+ const order = await ctx.runQuery(mode.refs.getOrder, { orderId })
54
+ if (order?.entityId === userId) return order
55
+ throw backendError('forbidden', { reason: 'not_owner' }, '[nuxt-backend] getInvoiceUrl: that order is not on this billing account.')
56
+ }
57
+
58
+ const getInvoiceUrl: Billing['getInvoiceUrl'] = async (ctx, orderId) => {
59
+ const { userId } = await requireEntity(ctx, BILLING_ACCESS.records)
60
+ if (!accessToken) return null
61
+ await throttle(ctx, userId, 'invoice reads')
62
+ await ownOrder(ctx, userId, orderId)
63
+ const invoice = await commerceCall('invoice read', () => mode.client().invoice(orderId))
64
+ if (invoice.kind === 'url') return { url: invoice.url }
65
+ // A provider that answers the PDF itself (Dodo): kept in file storage, for a URL to it.
66
+ const storage = (ctx as { storage?: { store: (blob: Blob) => Promise<string>, getUrl: (id: string) => Promise<string | null> } }).storage
67
+ if (!storage) throw polarOnly(mode.name, 'an invoice PDF outside an action')
68
+ const url = await storage.getUrl(await storage.store(new Blob([invoice.bytes], { type: 'application/pdf' })))
69
+ return url ? { url } : null
70
+ }
71
+
72
+ const getUsageHistory: Billing['getUsageHistory'] = async (ctx) => {
73
+ await requireEntity(ctx, BILLING_ACCESS.read)
74
+ throw polarOnly(mode.name, 'usage history')
75
+ }
76
+
77
+ const refundOrder: Billing['refundOrder'] = async (ctx, options) => {
78
+ await requireAdmin(ctx, 'refundOrder', ADMIN_WRITE)
79
+ requireProviderAccess('refund')
80
+ const order = await ctx.runQuery(mode.refs.getOrder, { orderId: options.orderId })
81
+ if (!order) throw backendError('invalid_input', { field: 'orderId' }, `[nuxt-backend] refundOrder: order ${options.orderId} is not in the order ledger.`)
82
+ const amount = options.amount ?? order.amount - order.refundedAmount
83
+ if (!(amount > 0)) {
84
+ throw backendError('invalid_input', { field: 'amount' }, `[nuxt-backend] refundOrder: order ${options.orderId} has nothing left to refund.`)
85
+ }
86
+ const refund = await commerceCall('refund', () => mode.client().refundOrder({
87
+ orderId: order.orderId,
88
+ ...(options.amount === undefined ? {} : { amount }),
89
+ ...(options.reason ? { reason: String(options.reason) } : {}),
90
+ idempotencyKey: `refund:${order.orderId}:${amount}:${order.refundedAmount}`,
91
+ }))
92
+ // The refund's delivery counts it on the ledger and takes the credits back.
93
+ await recordEvent(ctx, order.entityId, {
94
+ type: 'billing.refund_issued',
95
+ targetId: order.orderId,
96
+ data: { reason: String(options.reason ?? 'customer_request'), ...(options.amount === undefined ? {} : { amount }) },
97
+ })
98
+ return {
99
+ id: refund.id,
100
+ orderId: refund.orderId ?? order.orderId,
101
+ status: refund.status,
102
+ reason: String(options.reason ?? 'customer_request'),
103
+ amount: refund.amount ?? amount,
104
+ currency: refund.currency ?? order.currency,
105
+ revokeBenefits: true,
106
+ }
107
+ }
108
+
109
+ return { getOrders, getInvoiceUrl, getUsageHistory, refundOrder }
110
+ }
@@ -0,0 +1,69 @@
1
+ import { handleWebhookDelivery, type WebhookLogRefs } from '../webhook-guard.js'
2
+ import type { CommerceProvider, NeutralBillingEvent } from './providers/types.js'
3
+
4
+ // `/billing/events` for a provider on the neutral adapters (Stripe Managed
5
+ // Payments, Dodo, Creem): the same guarded edge Polar's deliveries go
6
+ // through (webhook-guard.ts: 503 without a secret, 413 over the cap, the
7
+ // redelivery dedupe, the delivery log), with the adapter's verifier and its
8
+ // neutral reading of the event in place of Polar's SDK.
9
+
10
+ /** What the app does with a verified, neutral billing event. It must be idempotent: a provider retries until it gets a 2xx. */
11
+ export type CommerceEventHandler<Ctx> = (ctx: Ctx, event: NeutralBillingEvent, delivery: { id: string }) => Promise<void>
12
+
13
+ /** The options of {@link createCommerceWebhookHandler}. */
14
+ export interface CommerceWebhookOptions<Ctx> {
15
+ provider: CommerceProvider
16
+ /** The accepted signing secrets, first entry primary (`BILLING_WEBHOOK_SECRET`, comma-separated while rotating). */
17
+ secrets: readonly string[]
18
+ /** `components.backend.webhooks`: the delivery log the dedupe reads. */
19
+ webhookLog: WebhookLogRefs
20
+ onEvent: CommerceEventHandler<Ctx>
21
+ }
22
+
23
+ /** The delivery id a body names (Stripe's and Creem's event `id`), before anything verifies it. */
24
+ function bodyEventId(body: string): string | null {
25
+ try {
26
+ const id = (JSON.parse(body) as { id?: unknown }).id
27
+ return typeof id === 'string' && id.length <= 200 ? id : null
28
+ }
29
+ catch {
30
+ return null
31
+ }
32
+ }
33
+
34
+ /**
35
+ * The handler an app passes as `billing.webhookHandler` to `registerBackendRoutes`
36
+ * for an adapter provider. `BILLING_PROVIDER` does not mount it.
37
+ *
38
+ * @experimental
39
+ */
40
+ export function createCommerceWebhookHandler<Ctx>({ provider, secrets, webhookLog, onEvent }: CommerceWebhookOptions<Ctx>) {
41
+ return (ctx: Ctx, request: Request): Promise<Response> => handleWebhookDelivery(ctx, webhookLog, {
42
+ service: 'billing',
43
+ // The id the signature covers: Dodo signs to Standard Webhooks, which
44
+ // covers the `webhook-id` header; Stripe and Creem sign the body alone,
45
+ // so a header there could be changed on a replay to slip the dedupe.
46
+ deliveryId: provider.name === 'dodo' ? request.headers.get('webhook-id') : null,
47
+ bodyDeliveryId: bodyEventId,
48
+ request,
49
+ secretsConfigured: secrets.length > 0,
50
+ verify: async (_parsed, body) => {
51
+ let verified
52
+ try {
53
+ verified = await provider.verifyWebhook(body, request.headers, secrets)
54
+ }
55
+ catch (error) {
56
+ // A signature that verified over a body that is no JSON: nothing can run.
57
+ return { outcome: 'handler_error', note: `${provider.name} delivery could not be read: ${error instanceof Error ? error.name : 'error'}`, response: new Response('Unreadable event', { status: 400 }) }
58
+ }
59
+ if (!verified) return { outcome: 'invalid_signature' }
60
+ const { event } = verified
61
+ if (event.type === 'ignored') {
62
+ // The delivery log keeps its type, noted ignored: nothing the package keeps changed.
63
+ return { outcome: 'ok', type: event.providerType, note: 'ignored', response: new Response('OK', { status: 200 }) }
64
+ }
65
+ await onEvent(ctx, event, { id: verified.id })
66
+ return { outcome: 'ok', type: event.providerType, response: new Response('OK', { status: 200 }) }
67
+ },
68
+ })
69
+ }