better-auth-flutterwave 0.4.3 → 1.0.1

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 (36) hide show
  1. package/README.es-ES.md +73 -346
  2. package/README.fr-FR.md +76 -346
  3. package/README.md +93 -344
  4. package/dist/client.d.mts +5 -6
  5. package/dist/client.d.mts.map +1 -1
  6. package/dist/client.mjs +2 -3
  7. package/dist/client.mjs.map +1 -1
  8. package/dist/{index-BqoHQ7eU.d.mts → index-CWQ-yaXU.d.mts} +17 -151
  9. package/dist/index-CWQ-yaXU.d.mts.map +1 -0
  10. package/dist/index.d.mts +1 -1
  11. package/dist/index.mjs +33 -46
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/{version-eSGk9I11.mjs → version-CvBysHjX.mjs} +4 -6
  14. package/dist/{version-eSGk9I11.mjs.map → version-CvBysHjX.mjs.map} +1 -1
  15. package/package.json +15 -17
  16. package/skills/better-auth-flutterwave-setup/SKILL.md +15 -14
  17. package/skills/better-auth-flutterwave-setup/agents/openai.yaml +1 -1
  18. package/skills/flutterwave-billing-flows/SKILL.md +19 -12
  19. package/skills/flutterwave-billing-flows/agents/openai.yaml +1 -1
  20. package/skills/flutterwave-catalog-limits/SKILL.md +15 -9
  21. package/skills/flutterwave-catalog-limits/agents/openai.yaml +1 -1
  22. package/skills/flutterwave-client-api/SKILL.md +16 -12
  23. package/skills/flutterwave-client-api/agents/openai.yaml +1 -1
  24. package/skills/flutterwave-local-subscriptions/SKILL.md +16 -17
  25. package/skills/flutterwave-local-subscriptions/agents/openai.yaml +1 -1
  26. package/skills/flutterwave-organization-billing/SKILL.md +14 -9
  27. package/skills/flutterwave-organization-billing/agents/openai.yaml +1 -1
  28. package/skills/flutterwave-schema-migrations/SKILL.md +16 -16
  29. package/skills/flutterwave-schema-migrations/agents/openai.yaml +1 -1
  30. package/skills/flutterwave-tanstack-start/SKILL.md +15 -17
  31. package/skills/flutterwave-tanstack-start/agents/openai.yaml +1 -1
  32. package/skills/flutterwave-testing-fixtures/SKILL.md +17 -11
  33. package/skills/flutterwave-testing-fixtures/agents/openai.yaml +1 -1
  34. package/skills/flutterwave-webhooks-events/SKILL.md +17 -13
  35. package/skills/flutterwave-webhooks-events/agents/openai.yaml +1 -1
  36. package/dist/index-BqoHQ7eU.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["NodeBuffer","NodeBuffer","adapter"],"sources":["../src/billing-store.ts","../src/flutterwave-contracts.ts","../src/flutterwave-sdk.ts","../src/operation-ledger.ts","../src/token-crypto.ts","../src/utils.ts","../src/billing-lifecycle.ts","../src/reference-access.ts","../src/route-modules/webhook.ts","../src/route-modules/shared.ts","../src/routes.ts","../src/schema.ts","../src/flutterwave-v4.ts","../src/limits.ts","../src/operations.ts","../src/reconciliation.ts","../src/index.ts"],"sourcesContent":["/* oxlint-disable typescript/no-unnecessary-type-assertion */\nimport type { GenericEndpointContext } from \"better-auth\";\n\nimport type {\n FlutterwavePlan,\n FlutterwaveProduct,\n FlutterwaveRefund,\n FlutterwaveSubscription,\n FlutterwaveTransaction,\n FlutterwaveWebhookEventRecord,\n Member,\n Organization,\n User,\n} from \"./types.ts\";\n\nexport type BillingStoreAdapter = Pick<\n GenericEndpointContext[\"context\"][\"adapter\"],\n \"create\" | \"findOne\" | \"findMany\" | \"update\" | \"updateMany\"\n>;\ntype WhereValue = string | number | boolean | Date | null;\ntype WhereClause = { field: string; value: WhereValue }[];\n\nexport interface BillingStore {\n findSubscriptionById(id: string): Promise<FlutterwaveSubscription | null>;\n findSubscriptionByProviderId(subscriptionId: number): Promise<FlutterwaveSubscription | null>;\n findSubscriptionsByReference(referenceId: string): Promise<FlutterwaveSubscription[]>;\n findCurrentSubscription(\n referenceId: string,\n groupId?: string | null,\n ): Promise<FlutterwaveSubscription | null>;\n retireCompetingSubscriptions(\n referenceId: string,\n groupId: string | null,\n exceptId: string,\n ): Promise<void>;\n findSubscriptionsByTxRef(txRef: string): Promise<FlutterwaveSubscription[]>;\n findSubscriptionsByBillingEmailAndPlanId(\n email: string,\n paymentPlanId: number,\n ): Promise<FlutterwaveSubscription[]>;\n listDueCancellations(now: Date, limit: number): Promise<FlutterwaveSubscription[]>;\n completeScheduledCancellation(subscription: FlutterwaveSubscription, now: Date): Promise<boolean>;\n createSubscription(\n data: Partial<FlutterwaveSubscription> & Record<string, unknown>,\n ): Promise<FlutterwaveSubscription>;\n updateSubscription(\n id: string,\n update: Partial<FlutterwaveSubscription> & Record<string, unknown>,\n ): Promise<FlutterwaveSubscription | null>;\n updateCurrentSubscription(\n subscription: FlutterwaveSubscription,\n update: Partial<FlutterwaveSubscription> & Record<string, unknown>,\n ): Promise<boolean>;\n updateSubscriptionByProviderId(\n subscriptionId: number,\n update: Partial<FlutterwaveSubscription> & Record<string, unknown>,\n ): Promise<FlutterwaveSubscription | null>;\n createTransaction(\n data: Partial<FlutterwaveTransaction> & Record<string, unknown>,\n ): Promise<FlutterwaveTransaction>;\n findTransactionByTxRef(txRef: string): Promise<FlutterwaveTransaction | null>;\n findTransactionById(transactionId: number): Promise<FlutterwaveTransaction | null>;\n updateTransactionByTxRef(\n txRef: string,\n update: Partial<FlutterwaveTransaction> & Record<string, unknown>,\n ): Promise<FlutterwaveTransaction | null>;\n listTransactions(referenceId: string): Promise<FlutterwaveTransaction[]>;\n listProducts(): Promise<FlutterwaveProduct[]>;\n findProductByName(name: string): Promise<FlutterwaveProduct | null>;\n findProductBySlug(slug: string): Promise<FlutterwaveProduct | null>;\n updateProduct(\n id: string,\n update: Partial<FlutterwaveProduct> & Record<string, unknown>,\n ): Promise<void>;\n upsertProductBySlug(\n slug: string,\n data: Partial<FlutterwaveProduct> & Record<string, unknown>,\n ): Promise<void>;\n listPlans(): Promise<FlutterwavePlan[]>;\n findPlanByName(name: string): Promise<FlutterwavePlan | null>;\n findPlanByPaymentPlanId(paymentPlanId: number): Promise<FlutterwavePlan | null>;\n upsertPlanByPaymentPlanId(\n paymentPlanId: number,\n data: Partial<FlutterwavePlan> & Record<string, unknown>,\n ): Promise<void>;\n createWebhookEvent(\n data: Partial<FlutterwaveWebhookEventRecord> & Record<string, unknown>,\n ): Promise<FlutterwaveWebhookEventRecord>;\n findWebhookEvent(eventId: string): Promise<FlutterwaveWebhookEventRecord | null>;\n updateWebhookEvent(\n eventId: string,\n update: Partial<FlutterwaveWebhookEventRecord> & Record<string, unknown>,\n ): Promise<FlutterwaveWebhookEventRecord | null>;\n claimWebhookEvent(event: FlutterwaveWebhookEventRecord, now: Date): Promise<boolean>;\n updateOwnedWebhookEvent(\n event: FlutterwaveWebhookEventRecord,\n update: Partial<FlutterwaveWebhookEventRecord>,\n ): Promise<boolean>;\n createRefund(\n data: Partial<FlutterwaveRefund> & Record<string, unknown>,\n ): Promise<FlutterwaveRefund>;\n findRefundByProviderId(refundId: number): Promise<FlutterwaveRefund | null>;\n listPendingRefunds(): Promise<FlutterwaveRefund[]>;\n updateRefund(\n id: string,\n update: Partial<FlutterwaveRefund> & Record<string, unknown>,\n ): Promise<FlutterwaveRefund | null>;\n findUser(id: string): Promise<User | null>;\n findOrganization(id: string): Promise<Organization | null>;\n findOrganizationOwner(organizationId: string): Promise<Member | null>;\n listMembers(organizationId: string): Promise<Member[]>;\n listTeams(organizationId: string): Promise<unknown[]>;\n}\n\nfunction sortSubscriptionsForCurrent(\n subscriptions: FlutterwaveSubscription[],\n): FlutterwaveSubscription[] {\n const statusRank = new Map([\n [\"active\", 0],\n [\"trialing\", 1],\n [\"incomplete\", 2],\n [\"past_due\", 3],\n [\"canceled\", 4],\n ]);\n return [...subscriptions].sort((a, b) => {\n const statusDifference = (statusRank.get(a.status) ?? 99) - (statusRank.get(b.status) ?? 99);\n return statusDifference !== 0\n ? statusDifference\n : new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();\n });\n}\n\nexport function createBillingStore(ctx: {\n context: { adapter: BillingStoreAdapter };\n}): BillingStore {\n return createBillingStoreFromAdapter(ctx.context.adapter);\n}\n\nexport function createBillingStoreFromAdapter(adapter: BillingStoreAdapter): BillingStore {\n const findOne = async <T>(model: string, where: WhereClause): Promise<T | null> =>\n (await adapter.findOne<T>({ model, where })) ?? null;\n const findMany = async <T>(model: string, where?: WhereClause): Promise<T[]> =>\n (await adapter.findMany<T>({ model, ...(where ? { where } : {}) })) ?? [];\n\n return {\n findSubscriptionById: (id) => findOne(\"flutterwaveSubscription\", [{ field: \"id\", value: id }]),\n findSubscriptionByProviderId: (subscriptionId) =>\n findOne(\"flutterwaveSubscription\", [{ field: \"subscriptionId\", value: subscriptionId }]),\n findSubscriptionsByReference: (referenceId) =>\n findMany(\"flutterwaveSubscription\", [{ field: \"referenceId\", value: referenceId }]),\n async findCurrentSubscription(referenceId, groupId) {\n const candidates = await this.findSubscriptionsByReference(referenceId);\n const scoped =\n groupId === undefined\n ? candidates\n : candidates.filter(({ groupId: candidateGroup }) =>\n groupId === null\n ? candidateGroup === undefined || candidateGroup === null || candidateGroup === \"\"\n : candidateGroup === groupId,\n );\n return sortSubscriptionsForCurrent(scoped)[0] ?? null;\n },\n async retireCompetingSubscriptions(referenceId, groupId, exceptId) {\n const candidates = await this.findSubscriptionsByReference(referenceId);\n const current = candidates.find(({ id }) => id === exceptId);\n if (!current) return;\n const now = new Date();\n for (const candidate of candidates) {\n const sameGroup =\n groupId === null\n ? candidate.groupId === undefined ||\n candidate.groupId === null ||\n candidate.groupId === \"\"\n : candidate.groupId === groupId;\n if (\n candidate.id !== exceptId &&\n new Date(candidate.createdAt).getTime() <= new Date(current.createdAt).getTime() &&\n sameGroup &&\n [\"active\", \"trialing\", \"incomplete\", \"past_due\"].includes(candidate.status)\n ) {\n await this.updateSubscription(candidate.id, {\n status: \"canceled\",\n cancelAtPeriodEnd: false,\n canceledAt: now,\n endedAt: now,\n updatedAt: now,\n });\n }\n }\n },\n findSubscriptionsByTxRef: (txRef) =>\n findMany(\"flutterwaveSubscription\", [{ field: \"txRef\", value: txRef }]),\n findSubscriptionsByBillingEmailAndPlanId: (email, paymentPlanId) =>\n findMany(\"flutterwaveSubscription\", [\n { field: \"billingEmail\", value: email },\n { field: \"paymentPlanId\", value: paymentPlanId },\n ]),\n listDueCancellations: (now, limit) =>\n adapter.findMany({\n model: \"flutterwaveSubscription\",\n where: [\n { field: \"cancelAtPeriodEnd\", value: true },\n { field: \"cancelAt\", value: now, operator: \"lte\" },\n ],\n sortBy: { field: \"cancelAt\", direction: \"asc\" },\n limit,\n }),\n async completeScheduledCancellation(subscription, now) {\n const count = await adapter.updateMany({\n model: \"flutterwaveSubscription\",\n where: [\n { field: \"id\", value: subscription.id },\n { field: \"cancelAtPeriodEnd\", value: true },\n {\n field: \"cancelAt\",\n value: subscription.cancelAt == null ? null : new Date(subscription.cancelAt),\n },\n ],\n update: {\n status: \"canceled\",\n cancelAtPeriodEnd: false,\n canceledAt: subscription.canceledAt ?? now,\n endedAt: subscription.cancelAt ?? now,\n updatedAt: now,\n },\n });\n return count === 1;\n },\n createSubscription: (data) =>\n adapter.create({\n model: \"flutterwaveSubscription\",\n data,\n }) as Promise<FlutterwaveSubscription>,\n updateSubscription: (id, update) =>\n adapter.update({\n model: \"flutterwaveSubscription\",\n update,\n where: [{ field: \"id\", value: id }],\n }),\n async updateCurrentSubscription(subscription, update) {\n const count = await adapter.updateMany({\n model: \"flutterwaveSubscription\",\n where: [\n { field: \"id\", value: subscription.id },\n { field: \"status\", value: subscription.status },\n { field: \"txRef\", value: subscription.txRef ?? null },\n ],\n update,\n });\n return count === 1;\n },\n updateSubscriptionByProviderId: (subscriptionId, update) =>\n adapter.update({\n model: \"flutterwaveSubscription\",\n update,\n where: [{ field: \"subscriptionId\", value: subscriptionId }],\n }),\n createTransaction: (data) =>\n adapter.create({ model: \"flutterwaveTransaction\", data }) as Promise<FlutterwaveTransaction>,\n findTransactionByTxRef: (txRef) =>\n findOne(\"flutterwaveTransaction\", [{ field: \"txRef\", value: txRef }]),\n findTransactionById: (transactionId) =>\n findOne(\"flutterwaveTransaction\", [{ field: \"transactionId\", value: transactionId }]),\n updateTransactionByTxRef: (txRef, update) =>\n adapter.update({\n model: \"flutterwaveTransaction\",\n update,\n where: [{ field: \"txRef\", value: txRef }],\n }),\n async listTransactions(referenceId) {\n const values = await findMany<FlutterwaveTransaction>(\"flutterwaveTransaction\", [\n { field: \"referenceId\", value: referenceId },\n ]);\n return values.sort(\n (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n );\n },\n async listProducts() {\n const values = await findMany<FlutterwaveProduct>(\"flutterwaveProduct\");\n return values.sort((a, b) => a.name.localeCompare(b.name));\n },\n findProductByName: (name) => findOne(\"flutterwaveProduct\", [{ field: \"name\", value: name }]),\n findProductBySlug: (slug) => findOne(\"flutterwaveProduct\", [{ field: \"slug\", value: slug }]),\n async updateProduct(id, update) {\n await adapter.update({\n model: \"flutterwaveProduct\",\n update,\n where: [{ field: \"id\", value: id }],\n });\n },\n async upsertProductBySlug(slug, data) {\n const existing = await this.findProductBySlug(slug);\n if (existing?.id !== undefined) {\n const { createdAt: _createdAt, ...update } = data;\n await this.updateProduct(existing.id, update);\n } else {\n await adapter.create({ model: \"flutterwaveProduct\", data: { ...data, slug } });\n }\n },\n listPlans: () => findMany(\"flutterwavePlan\"),\n findPlanByName: (name) => findOne(\"flutterwavePlan\", [{ field: \"name\", value: name }]),\n findPlanByPaymentPlanId: (paymentPlanId) =>\n findOne(\"flutterwavePlan\", [{ field: \"paymentPlanId\", value: paymentPlanId }]),\n async upsertPlanByPaymentPlanId(paymentPlanId, data) {\n const existing = await this.findPlanByPaymentPlanId(paymentPlanId);\n if (existing?.id !== undefined) {\n const { createdAt: _createdAt, ...update } = data;\n await adapter.update({\n model: \"flutterwavePlan\",\n update,\n where: [{ field: \"id\", value: existing.id }],\n });\n } else {\n await adapter.create({ model: \"flutterwavePlan\", data: { ...data, paymentPlanId } });\n }\n },\n createWebhookEvent: (data) =>\n adapter.create({\n model: \"flutterwaveWebhookEvent\",\n data,\n }) as Promise<FlutterwaveWebhookEventRecord>,\n findWebhookEvent: (eventId) =>\n findOne(\"flutterwaveWebhookEvent\", [{ field: \"eventId\", value: eventId }]),\n updateWebhookEvent: (eventId, update) =>\n adapter.update({\n model: \"flutterwaveWebhookEvent\",\n update,\n where: [{ field: \"eventId\", value: eventId }],\n }),\n async claimWebhookEvent(event, now) {\n const claimed = await adapter.updateMany({\n model: \"flutterwaveWebhookEvent\",\n where: [\n { field: \"eventId\", value: event.eventId },\n { field: \"status\", value: event.status },\n { field: \"updatedAt\", value: new Date(event.updatedAt) },\n ],\n update: { status: \"processing\", updatedAt: now },\n });\n return claimed === 1;\n },\n async updateOwnedWebhookEvent(event, update) {\n const count = await adapter.updateMany({\n model: \"flutterwaveWebhookEvent\",\n where: [\n { field: \"eventId\", value: event.eventId },\n { field: \"status\", value: \"processing\" },\n { field: \"updatedAt\", value: new Date(event.updatedAt) },\n ],\n update,\n });\n return count === 1;\n },\n createRefund: (data) =>\n adapter.create({ model: \"flutterwaveRefund\", data }) as Promise<FlutterwaveRefund>,\n findRefundByProviderId: (refundId) =>\n findOne(\"flutterwaveRefund\", [{ field: \"refundId\", value: refundId }]),\n listPendingRefunds: () =>\n adapter.findMany({\n model: \"flutterwaveRefund\",\n where: [\n {\n field: \"status\",\n operator: \"in\",\n value: [\"pending\", \"completed\", \"processing\", \"pending-momo\"],\n },\n ],\n }),\n updateRefund: (id, update) =>\n adapter.update({ model: \"flutterwaveRefund\", update, where: [{ field: \"id\", value: id }] }),\n findUser: (id) => findOne(\"user\", [{ field: \"id\", value: id }]),\n findOrganization: (id) => findOne(\"organization\", [{ field: \"id\", value: id }]),\n findOrganizationOwner: (organizationId) =>\n findOne(\"member\", [\n { field: \"organizationId\", value: organizationId },\n { field: \"role\", value: \"owner\" },\n ]),\n listMembers: (organizationId) =>\n findMany(\"member\", [{ field: \"organizationId\", value: organizationId }]),\n listTeams: (organizationId) =>\n findMany(\"team\", [{ field: \"organizationId\", value: organizationId }]),\n };\n}\n","/* oxlint-disable no-restricted-imports */\nimport * as z from \"zod\";\n\nconst currencySchema = z.string().regex(/^[A-Z]{3}$/, \"Currency must be a three-letter ISO code\");\nconst positiveAmountSchema = z.coerce.number().positive();\nconst optionalDateSchema = z.string().nullable().optional();\n\nexport const flutterwaveEnvelopeSchema = <T extends z.ZodType>(data: T) =>\n z\n .object({\n status: z.string(),\n message: z.string().optional(),\n data,\n })\n .passthrough();\n\nexport const standardCheckoutInputSchema = z\n .object({\n tx_ref: z.string().min(1).max(100),\n amount: positiveAmountSchema,\n currency: currencySchema,\n redirect_url: z.url(),\n customer: z\n .object({\n email: z.email(),\n name: z.string().min(1).optional(),\n phonenumber: z.string().min(1).optional(),\n })\n .passthrough(),\n payment_options: z.string().min(1).optional(),\n payment_plan: z.number().int().positive().optional(),\n subaccounts: z\n .array(\n z\n .object({\n id: z.string().min(1),\n transaction_charge_type: z.enum([\"flat\", \"percentage\"]).optional(),\n transaction_charge: z.number().nonnegative().optional(),\n })\n .passthrough(),\n )\n .min(1)\n .optional(),\n customizations: z\n .object({\n title: z.string().optional(),\n description: z.string().optional(),\n logo: z.url().optional(),\n })\n .optional(),\n meta: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough();\n\nexport const checkoutDataSchema = z\n .object({\n link: z.url(),\n })\n .passthrough();\n\nexport const transactionSchema = z\n .object({\n id: z.coerce.number().int().positive(),\n tx_ref: z.string().min(1),\n flw_ref: z.string().nullable().optional(),\n amount: positiveAmountSchema,\n charged_amount: z.coerce.number().nonnegative().optional(),\n currency: currencySchema,\n status: z.string().min(1),\n payment_type: z.string().nullable().optional(),\n created_at: optionalDateSchema,\n customer: z\n .object({\n id: z.coerce.number().int().optional(),\n email: z.email(),\n name: z.string().nullable().optional(),\n })\n .passthrough()\n .optional(),\n card: z\n .object({\n token: z.string().min(1).optional(),\n })\n .passthrough()\n .nullable()\n .optional(),\n })\n .passthrough();\n\nexport const paymentPlanSchema = z\n .object({\n id: z.coerce.number().int().positive(),\n name: z.string().min(1),\n amount: positiveAmountSchema\n .nullable()\n .optional()\n .transform((value) => value ?? undefined),\n interval: z.string().min(1),\n currency: currencySchema,\n status: z.string().optional(),\n duration: z.coerce.number().int().nonnegative().optional(),\n created_at: optionalDateSchema,\n })\n .passthrough();\n\nexport const subscriptionSchema = z\n .object({\n id: z.coerce.number().int().positive(),\n amount: positiveAmountSchema,\n customer: z\n .object({\n email: z.email().optional(),\n customer_email: z.email().optional(),\n })\n .passthrough()\n .optional(),\n plan: z.coerce.number().int().positive().optional(),\n status: z.string().min(1),\n currency: currencySchema.optional(),\n created_at: optionalDateSchema,\n })\n .passthrough();\n\nexport const tokenChargeInputSchema = z\n .object({\n token: z.string().min(1),\n currency: currencySchema,\n country: z.string().length(2).toUpperCase().optional(),\n amount: positiveAmountSchema,\n email: z.email(),\n tx_ref: z.string().min(1).max(100),\n narration: z.string().optional(),\n })\n .passthrough();\n\nexport const refundSchema = z\n .object({\n id: z.coerce.number().int().positive().optional(),\n transaction_id: z.coerce.number().int().positive().optional(),\n amount_refunded: z.coerce.number().nonnegative().optional(),\n amount: z.coerce.number().nonnegative().optional(),\n status: z.string().min(1),\n created_at: optionalDateSchema,\n })\n .passthrough();\n\nexport type StandardCheckoutInput = z.infer<typeof standardCheckoutInputSchema>;\nexport type FlutterwaveCheckoutData = z.infer<typeof checkoutDataSchema>;\nexport type FlutterwaveTransactionData = z.infer<typeof transactionSchema>;\nexport type FlutterwavePaymentPlanData = z.infer<typeof paymentPlanSchema>;\nexport type FlutterwaveSubscriptionData = z.infer<typeof subscriptionSchema>;\nexport type FlutterwaveTokenChargeInput = z.infer<typeof tokenChargeInputSchema>;\nexport type FlutterwaveRefundData = z.infer<typeof refundSchema>;\n","/* oxlint-disable no-restricted-imports */\nimport * as z from \"zod\";\nimport {\n checkoutDataSchema,\n flutterwaveEnvelopeSchema,\n paymentPlanSchema,\n refundSchema,\n standardCheckoutInputSchema,\n subscriptionSchema,\n tokenChargeInputSchema,\n transactionSchema,\n type FlutterwaveCheckoutData,\n type FlutterwavePaymentPlanData,\n type FlutterwaveRefundData,\n type FlutterwaveSubscriptionData,\n type FlutterwaveTokenChargeInput,\n type FlutterwaveTransactionData,\n type StandardCheckoutInput,\n} from \"./flutterwave-contracts.ts\";\n\ntype SdkResult = Promise<unknown>;\n\n/** The deliberately small provider boundary used by this package. */\nexport interface FlutterwaveClient {\n Transaction: {\n verify(input: { id: number }): SdkResult;\n verify_by_tx(input: { tx_ref: string }): SdkResult;\n refund(input: { id: number; amount?: number; comments?: string }): SdkResult;\n };\n PaymentPlan: {\n get_all(input: Record<string, unknown>): SdkResult;\n };\n Subscription: {\n fetch_all(input: Record<string, unknown>): SdkResult;\n cancel(input: { id: number }): SdkResult;\n activate(input: { id: number }): SdkResult;\n };\n Tokenized: {\n charge(input: FlutterwaveTokenChargeInput): SdkResult;\n };\n}\n\n/** @deprecated Use FlutterwaveClient. */\nexport type FlutterwaveSdkClient = FlutterwaveClient;\n\nexport interface FlutterwaveAdapterOptions {\n publicKey: string;\n secretKey: string;\n flutterwaveClient?: FlutterwaveClient;\n fetch?: typeof globalThis.fetch;\n apiBaseUrl?: string;\n}\n\nexport interface VerifyTransactionInput {\n transactionId?: number;\n txRef?: string;\n}\n\nexport interface ListSubscriptionsInput {\n email?: string;\n transactionId?: number;\n plan?: number;\n status?: string;\n page?: number;\n}\n\nexport interface FlutterwaveAdapter {\n initializePayment(input: StandardCheckoutInput): Promise<FlutterwaveCheckoutData>;\n verifyTransaction(input: VerifyTransactionInput): Promise<FlutterwaveTransactionData>;\n listPaymentPlans(): Promise<FlutterwavePaymentPlanData[]>;\n listSubscriptions(input?: ListSubscriptionsInput): Promise<FlutterwaveSubscriptionData[]>;\n cancelSubscription(subscriptionId: number): Promise<FlutterwaveSubscriptionData>;\n activateSubscription(subscriptionId: number): Promise<FlutterwaveSubscriptionData>;\n chargeToken(input: FlutterwaveTokenChargeInput): Promise<FlutterwaveTransactionData>;\n refundTransaction(\n transactionId: number,\n amount?: number,\n reason?: string,\n ): Promise<FlutterwaveRefundData>;\n}\n\nexport class FlutterwaveAdapterError extends Error {\n readonly operation: string;\n readonly status?: number;\n readonly cause?: unknown;\n\n constructor(operation: string, message: string, options?: { status?: number; cause?: unknown }) {\n super(message);\n this.name = \"FlutterwaveAdapterError\";\n this.operation = operation;\n this.status = options?.status;\n this.cause = options?.cause;\n }\n}\n\nfunction queryString(input: Record<string, unknown>): string {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(input)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n query.set(key, String(value));\n }\n }\n const serialized = query.toString();\n return serialized.length === 0 ? \"\" : `?${serialized}`;\n}\n\nfunction createHttpClient(\n fetchImpl: typeof globalThis.fetch,\n apiBaseUrl: string,\n secretKey: string,\n): FlutterwaveClient {\n const request = async (\n path: string,\n method: \"GET\" | \"POST\" | \"PUT\" = \"GET\",\n body?: unknown,\n ): Promise<unknown> => {\n if (typeof fetchImpl !== \"function\") throw new Error(\"Fetch is not available\");\n\n const response = await fetchImpl(`${apiBaseUrl}${path}`, {\n method,\n headers: {\n accept: \"application/json\",\n authorization: `Bearer ${secretKey}`,\n \"content-type\": \"application/json\",\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n\n let raw: unknown;\n try {\n raw = await response.json();\n } catch {\n throw new Error(`Flutterwave returned a non-JSON response (HTTP ${response.status})`);\n }\n\n if (!response.ok) {\n throw new Error(\n messageFromUnknown(raw) ?? `Flutterwave request failed with HTTP ${response.status}`,\n );\n }\n return raw;\n };\n\n const post = (path: string, body: unknown) => request(path, \"POST\", body);\n\n return {\n Transaction: {\n verify: ({ id }) => request(`/v3/transactions/${id}/verify`),\n verify_by_tx: ({ tx_ref }) =>\n request(`/v3/transactions/verify_by_reference${queryString({ tx_ref })}`),\n refund: ({ id, amount, comments }) =>\n post(`/v3/transactions/${id}/refund`, {\n ...(amount === undefined ? {} : { amount }),\n ...(comments === undefined ? {} : { comments }),\n }),\n },\n PaymentPlan: {\n get_all: (query) => request(`/v3/payment-plans${queryString(query)}`),\n },\n Subscription: {\n fetch_all: (query) => request(`/v3/subscriptions${queryString(query)}`),\n cancel: ({ id }) => request(`/v3/subscriptions/${id}/cancel`, \"PUT\"),\n activate: ({ id }) => request(`/v3/subscriptions/${id}/activate`, \"PUT\"),\n },\n Tokenized: {\n charge: (input) => post(\"/v3/tokenized-charges\", input),\n },\n };\n}\n\nfunction messageFromUnknown(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (typeof value !== \"object\" || value === null) return undefined;\n const message = Reflect.get(value, \"message\");\n return typeof message === \"string\" ? message : undefined;\n}\n\nfunction parseEnvelope<T>(operation: string, raw: unknown, dataSchema: z.ZodType<T>): T {\n const envelope = flutterwaveEnvelopeSchema(dataSchema).safeParse(raw);\n if (!envelope.success) {\n throw new FlutterwaveAdapterError(operation, \"Flutterwave returned an invalid response\", {\n cause: envelope.error,\n });\n }\n if (envelope.data.status.toLowerCase() !== \"success\") {\n throw new FlutterwaveAdapterError(\n operation,\n envelope.data.message ?? \"Flutterwave rejected the request\",\n );\n }\n return envelope.data.data;\n}\n\nasync function sdkCall<T>(\n operation: string,\n action: () => Promise<unknown>,\n schema: z.ZodType<T>,\n): Promise<T> {\n try {\n return parseEnvelope(operation, await action(), schema);\n } catch (error) {\n if (error instanceof FlutterwaveAdapterError) throw error;\n throw new FlutterwaveAdapterError(\n operation,\n messageFromUnknown(error) ?? `Flutterwave ${operation} failed`,\n { cause: error },\n );\n }\n}\n\nconst positiveIdSchema = z.number().int().positive();\nconst optionalPositiveAmountSchema = z.number().positive().optional();\n\n/**\n * Creates the provider boundary used by the plugin.\n *\n * Uses Flutterwave's v3 HTTP API directly so applications do not need a separate\n * SDK dependency. Inject `flutterwaveClient` for a custom provider boundary or\n * `fetch` for controlled transport and tests.\n */\nexport function createFlutterwaveAdapter(options: FlutterwaveAdapterOptions): FlutterwaveAdapter {\n if (!options.publicKey)\n throw new FlutterwaveAdapterError(\"configuration\", \"publicKey is required\");\n if (!options.secretKey)\n throw new FlutterwaveAdapterError(\"configuration\", \"secretKey is required\");\n\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const configuredApiBaseUrl = options.apiBaseUrl ?? \"https://api.flutterwave.com\";\n let end = configuredApiBaseUrl.length;\n while (end > 0 && configuredApiBaseUrl.charCodeAt(end - 1) === 47) end--;\n const apiBaseUrl = configuredApiBaseUrl.slice(0, end);\n const client =\n options.flutterwaveClient ?? createHttpClient(fetchImpl, apiBaseUrl, options.secretKey);\n\n return {\n async initializePayment(input) {\n const body = standardCheckoutInputSchema.parse(input);\n if (typeof fetchImpl !== \"function\") {\n throw new FlutterwaveAdapterError(\"initialize payment\", \"Fetch is not available\");\n }\n\n let response: Response;\n try {\n response = await fetchImpl(`${apiBaseUrl}/v3/payments`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${options.secretKey}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n } catch (error) {\n throw new FlutterwaveAdapterError(\n \"initialize payment\",\n messageFromUnknown(error) ?? \"Flutterwave checkout request failed\",\n { cause: error },\n );\n }\n\n let raw: unknown;\n try {\n raw = await response.json();\n } catch (error) {\n throw new FlutterwaveAdapterError(\n \"initialize payment\",\n \"Flutterwave returned a non-JSON response\",\n { status: response.status, cause: error },\n );\n }\n if (!response.ok) {\n throw new FlutterwaveAdapterError(\n \"initialize payment\",\n messageFromUnknown(raw) ?? `Flutterwave checkout failed with HTTP ${response.status}`,\n { status: response.status },\n );\n }\n return parseEnvelope(\"initialize payment\", raw, checkoutDataSchema);\n },\n\n async verifyTransaction(input) {\n if ((input.transactionId === undefined) === (input.txRef === undefined)) {\n throw new FlutterwaveAdapterError(\n \"verify transaction\",\n \"Provide exactly one of transactionId or txRef\",\n );\n }\n return input.transactionId !== undefined\n ? sdkCall(\n \"verify transaction\",\n () => client.Transaction.verify({ id: positiveIdSchema.parse(input.transactionId) }),\n transactionSchema,\n )\n : sdkCall(\n \"verify transaction\",\n () => client.Transaction.verify_by_tx({ tx_ref: z.string().min(1).parse(input.txRef) }),\n transactionSchema,\n );\n },\n\n listPaymentPlans: () =>\n sdkCall(\n \"list payment plans\",\n () => client.PaymentPlan.get_all({}),\n z.array(paymentPlanSchema),\n ),\n\n listSubscriptions: (input = {}) => {\n // Flutterwave's v3 query parameters are serialized as strings while this\n // adapter keeps numeric identifiers in its public interface.\n const query = {\n email: input.email,\n status: input.status,\n ...(input.plan === undefined ? {} : { plan: String(input.plan) }),\n ...(input.transactionId === undefined\n ? {}\n : { transaction_id: String(input.transactionId) }),\n ...(input.page === undefined ? {} : { page: String(input.page) }),\n };\n return sdkCall(\n \"list subscriptions\",\n () => client.Subscription.fetch_all(query),\n z.array(subscriptionSchema),\n );\n },\n\n cancelSubscription: (subscriptionId) =>\n sdkCall(\n \"cancel subscription\",\n () => client.Subscription.cancel({ id: positiveIdSchema.parse(subscriptionId) }),\n subscriptionSchema,\n ),\n\n activateSubscription: (subscriptionId) =>\n sdkCall(\n \"activate subscription\",\n () => client.Subscription.activate({ id: positiveIdSchema.parse(subscriptionId) }),\n subscriptionSchema,\n ),\n\n chargeToken: (input) => {\n const body = tokenChargeInputSchema.parse(input);\n return sdkCall(\"charge token\", () => client.Tokenized.charge(body), transactionSchema);\n },\n\n refundTransaction: (transactionId, amount, reason) =>\n sdkCall(\n \"refund transaction\",\n () =>\n client.Transaction.refund({\n id: positiveIdSchema.parse(transactionId),\n amount: optionalPositiveAmountSchema.parse(amount),\n ...(reason === undefined ? {} : { comments: z.string().min(1).parse(reason) }),\n }),\n refundSchema,\n ),\n };\n}\n\n/** @deprecated Parse SDK responses through a concrete adapter method instead. */\nexport function unwrapSdkResult<T>(result: unknown): T {\n if (typeof result === \"object\" && result !== null && \"data\" in result) {\n return Reflect.get(result, \"data\") as T;\n }\n return result as T;\n}\n\n/** @deprecated The adapter itself is now the operations boundary. */\nexport function getFlutterwaveOps<T>(client: T): T {\n return client;\n}\n","import { APIError } from \"better-auth/api\";\nimport type { BillingStore } from \"./billing-store.ts\";\nimport type { FlutterwaveWebhookEventRecord } from \"./types.ts\";\n\nconst LEASE_MS = 5 * 60_000;\n\nfunction busy(): APIError {\n return new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"Billing operation is in progress; retry later\",\n });\n}\n\n/** Internal operations share the existing unique event ledger; no new database schema is needed. */\nexport async function acquireOperation(\n store: BillingStore,\n input: { eventId: string; eventType: string; txRef: string; payload: string },\n): Promise<FlutterwaveWebhookEventRecord> {\n let existing = await store.findWebhookEvent(input.eventId);\n const now = new Date();\n if (existing === null) {\n try {\n return await store.createWebhookEvent({\n ...input,\n status: \"processing\",\n createdAt: now,\n updatedAt: now,\n });\n } catch (error) {\n existing = await store.findWebhookEvent(input.eventId);\n if (existing === null) throw error;\n }\n }\n if (existing.status === \"processed\") return existing;\n if (\n existing.status === \"processing\" &&\n new Date(existing.updatedAt).getTime() + LEASE_MS > now.getTime()\n )\n throw busy();\n // Distinct lease timestamps also protect callers that race within the same millisecond.\n const claimedAt = new Date(Math.max(now.getTime(), new Date(existing.updatedAt).getTime() + 1));\n if (!(await store.claimWebhookEvent(existing, claimedAt))) throw busy();\n return { ...existing, status: \"processing\", updatedAt: claimedAt };\n}\n\nexport async function checkpointOperation(\n store: BillingStore,\n operation: FlutterwaveWebhookEventRecord,\n update: Partial<FlutterwaveWebhookEventRecord>,\n): Promise<FlutterwaveWebhookEventRecord> {\n const updatedAt = new Date(Math.max(Date.now(), new Date(operation.updatedAt).getTime() + 1));\n if (!(await store.updateOwnedWebhookEvent(operation, { ...update, updatedAt }))) throw busy();\n return { ...operation, ...update, updatedAt };\n}\n\nexport async function failOperation(\n store: BillingStore,\n operation: FlutterwaveWebhookEventRecord,\n): Promise<void> {\n // A stale owner must not overwrite a lease acquired by another worker.\n await store.updateOwnedWebhookEvent(operation, { status: \"failed\", updatedAt: new Date() });\n}\n","const encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nfunction toBase64(value: Uint8Array): string {\n return NodeBuffer.from(value).toString(\"base64url\");\n}\n\nfunction fromBase64(value: string): Uint8Array {\n return new Uint8Array(NodeBuffer.from(value, \"base64url\"));\n}\n\nasync function deriveKey(secret: string): Promise<CryptoKey> {\n const digest = await crypto.subtle.digest(\"SHA-256\", encoder.encode(secret));\n return crypto.subtle.importKey(\"raw\", digest, \"AES-GCM\", false, [\"encrypt\", \"decrypt\"]);\n}\n\nexport async function encryptPaymentToken(token: string, secret: string): Promise<string> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const encrypted = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv },\n await deriveKey(secret),\n encoder.encode(token),\n );\n return `v1.${toBase64(iv)}.${toBase64(new Uint8Array(encrypted))}`;\n}\n\nexport async function decryptPaymentToken(value: string, secret: string): Promise<string> {\n const [version, encodedIv, encodedCiphertext] = value.split(\".\");\n if (version !== \"v1\" || !encodedIv || !encodedCiphertext) {\n throw new Error(\"Unsupported encrypted payment token\");\n }\n const iv = Uint8Array.from(fromBase64(encodedIv));\n const ciphertext = Uint8Array.from(fromBase64(encodedCiphertext));\n const decrypted = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv },\n await deriveKey(secret),\n ciphertext,\n );\n return decoder.decode(decrypted);\n}\nimport { Buffer as NodeBuffer } from \"node:buffer\";\n","import type { GenericEndpointContext } from \"better-auth\";\n\nimport type {\n AnyFlutterwaveOptions,\n FlutterwaveClientLike,\n FlutterwavePlan,\n FlutterwaveProduct,\n Subscription,\n} from \"./types.ts\";\nimport { createBillingStore } from \"./billing-store.ts\";\n\nexport function getPlanSeatAmount(plan: FlutterwavePlan): number | undefined {\n if (plan.seatAmount !== undefined) {\n if (\n typeof plan.seatAmount === \"number\" &&\n Number.isFinite(plan.seatAmount) &&\n plan.seatAmount >= 0\n ) {\n return plan.seatAmount;\n }\n throw new Error(`Invalid seatAmount for plan '${plan.name}'. Expected a finite number.`);\n }\n\n if (plan.seatPriceId === undefined || plan.seatPriceId === null || plan.seatPriceId === \"\") {\n return undefined;\n }\n\n const parsed = typeof plan.seatPriceId === \"string\" ? Number(plan.seatPriceId) : plan.seatPriceId;\n if (typeof parsed === \"number\" && Number.isFinite(parsed) && parsed >= 0) {\n return parsed;\n }\n\n throw new Error(\n `Invalid seatPriceId for plan '${plan.name}'. Expected a numeric amount in the smallest currency unit.`,\n );\n}\n\nexport function calculatePlanAmount(plan: FlutterwavePlan, quantity: number): number {\n return (plan.amount ?? 0) + Math.max(0, quantity - 1) * (getPlanSeatAmount(plan) ?? 0);\n}\n\nexport function normalizeSubscriptionGroup(group: string | undefined | null): string | null {\n const normalized = group?.trim().toLowerCase();\n return normalized === undefined || normalized === \"\" ? null : normalized;\n}\n\nexport function isLocallyManagedSubscription(\n subscription: Pick<Subscription, \"subscriptionId\" | \"paymentPlanId\">,\n): boolean {\n return subscription.subscriptionId === undefined || subscription.subscriptionId === null;\n}\n\nexport function assertLocallyManagedSubscription(\n subscription: Pick<Subscription, \"subscriptionId\" | \"paymentPlanId\">,\n action: string,\n): void {\n if (!isLocallyManagedSubscription(subscription)) {\n throw new Error(\n `Flutterwave-managed subscriptions do not support ${action}. Use local billing for seat-based or prorated subscription changes.`,\n );\n }\n}\n\nexport async function getPlans(\n subscriptionOptions: AnyFlutterwaveOptions[\"subscription\"],\n): Promise<FlutterwavePlan[]> {\n if (subscriptionOptions?.enabled === true) {\n return typeof subscriptionOptions.plans === \"function\"\n ? subscriptionOptions.plans()\n : subscriptionOptions.plans;\n }\n return [];\n}\n\nexport const getPlan: (\n options: AnyFlutterwaveOptions,\n planId: string,\n) => Promise<FlutterwavePlan | null> = async (options, planId) => {\n if (options.subscription?.enabled === true) {\n const plans = await getPlans(options.subscription);\n return plans.find((plan) => plan.name === planId) ?? null;\n }\n return null;\n};\n\nexport async function getPlanByName(\n options: AnyFlutterwaveOptions,\n name: string,\n): Promise<FlutterwavePlan | null> {\n if (typeof name !== \"string\" || name.trim() === \"\") {\n return null;\n }\n if (options.subscription?.enabled === true) {\n const plans = await getPlans(options.subscription);\n const normalizedName = name.toLowerCase();\n return (\n plans.find(\n (plan) => typeof plan.name === \"string\" && plan.name.toLowerCase() === normalizedName,\n ) ?? null\n );\n }\n return null;\n}\n\nexport async function getPlanByPriceId(\n options: AnyFlutterwaveOptions,\n priceId: string,\n): Promise<FlutterwavePlan | null> {\n if (options.subscription?.enabled === true) {\n const plans = await getPlans(options.subscription);\n return plans.find((plan) => plan.name === priceId) ?? null;\n }\n return null;\n}\n\nexport async function getProducts(\n productOptions: AnyFlutterwaveOptions[\"products\"],\n): Promise<FlutterwaveProduct[]> {\n if (productOptions?.products) {\n return typeof productOptions.products === \"function\"\n ? await productOptions.products()\n : productOptions.products;\n }\n return [];\n}\n\nexport async function getProductByName(\n options: AnyFlutterwaveOptions,\n name: string,\n): Promise<FlutterwaveProduct | null> {\n return await getProducts(options.products).then((products) =>\n products !== undefined && products !== null\n ? (products.find((product) => product.name.toLowerCase() === name.toLowerCase()) ?? null)\n : null,\n );\n}\n\nexport function getNextPeriodEnd(startDate: Date, interval: string): Date | null {\n const date = new Date(startDate);\n const day = date.getUTCDate();\n const addMonths = (months: number) => {\n date.setUTCDate(1);\n date.setUTCMonth(date.getUTCMonth() + months);\n const lastDay = new Date(\n Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0),\n ).getUTCDate();\n date.setUTCDate(Math.min(day, lastDay));\n };\n switch (interval) {\n case \"hourly\":\n date.setUTCHours(date.getUTCHours() + 1);\n break;\n case \"daily\":\n date.setUTCDate(date.getUTCDate() + 1);\n break;\n case \"weekly\":\n date.setUTCDate(date.getUTCDate() + 7);\n break;\n case \"monthly\":\n addMonths(1);\n break;\n case \"quarterly\":\n addMonths(3);\n break;\n case \"biannually\":\n case \"bi-annually\":\n addMonths(6);\n break;\n case \"annually\":\n case \"yearly\":\n addMonths(12);\n break;\n default: {\n const recurring = /^every (\\d+) (hours?|days?|weeks?|months?|years?)$/.exec(interval);\n if (!recurring) return null;\n const count = Number(recurring[1]);\n if (!Number.isSafeInteger(count) || count < 1) return null;\n const unit = recurring[2];\n if (unit?.startsWith(\"hour\")) date.setUTCHours(date.getUTCHours() + count);\n else if (unit?.startsWith(\"day\")) date.setUTCDate(date.getUTCDate() + count);\n else if (unit?.startsWith(\"week\")) date.setUTCDate(date.getUTCDate() + count * 7);\n else addMonths(count * (unit?.startsWith(\"year\") ? 12 : 1));\n if (!Number.isFinite(date.getTime())) return null;\n }\n }\n return date;\n}\n\n/**\n * Validates if the amount meets Flutterwave's minimum transaction requirements.\n * Amounts should be in the smallest currency unit (e.g., kobo, cents).\n */\nexport function validateMinAmount(amount: number, currency: string): boolean {\n const minAmounts: Record<string, number> = {\n NGN: 5000, // 50.00\n GHS: 10, // 0.10\n ZAR: 100, // 1.00\n KES: 300, // 3.00\n USD: 200, // 2.00\n XOF: 100, // 1.00\n };\n const min = minAmounts[currency.toUpperCase()];\n return min !== undefined ? amount >= min : true;\n}\n\nexport async function syncProductQuantityFromFlutterwave(\n ctx: GenericEndpointContext,\n productName: string,\n _flutterwaveClient: FlutterwaveClientLike,\n): Promise<void> {\n // Flutterwave does not provide a product catalogue. Inventory is authoritative locally.\n await decrementProductQuantity(ctx, productName);\n}\n\nexport async function decrementProductQuantity(\n ctx: GenericEndpointContext,\n productName: string,\n): Promise<void> {\n const store = createBillingStore(ctx);\n let product = await store.findProductByName(productName);\n\n product ??= await store.findProductBySlug(productName.toLowerCase().replace(/\\s+/g, \"-\"));\n\n if (product !== undefined && product !== null) {\n if (\n product.unlimited !== true &&\n typeof product.quantity === \"number\" &&\n product.quantity > 0 &&\n product.id !== undefined\n ) {\n await store.updateProduct(product.id, {\n quantity: product.quantity - 1,\n updatedAt: new Date(),\n });\n }\n }\n}\n\nexport async function syncSubscriptionSeats(\n ctx: GenericEndpointContext,\n organizationId: string,\n options: AnyFlutterwaveOptions,\n): Promise<void> {\n if (options.subscription?.enabled !== true) return;\n\n const store = createBillingStore(ctx);\n const subscriptions = (await store.findSubscriptionsByReference(organizationId)).filter(\n (subscription) => subscription.status === \"active\" || subscription.status === \"trialing\",\n );\n const seatSubscriptions: Subscription[] = [];\n for (const candidate of subscriptions) {\n const candidatePlan = await getPlanByName(options, candidate.plan);\n if (candidatePlan !== null && getPlanSeatAmount(candidatePlan) !== undefined) {\n seatSubscriptions.push(candidate);\n }\n }\n const members = await store.listMembers(organizationId);\n const quantity = members.length;\n for (const subscription of seatSubscriptions) {\n try {\n assertLocallyManagedSubscription(subscription, \"automatic seat sync\");\n\n // Locally managed subscriptions renew via saved authorizations, so seat count lives in our DB.\n await store.updateSubscription(subscription.id, {\n seats: quantity,\n updatedAt: new Date(),\n });\n } catch (e: unknown) {\n ctx.context.logger.error(\"Failed to sync subscription seats\", e);\n }\n }\n}\n","/* oxlint-disable no-restricted-imports */\nimport type { GenericEndpointContext } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\nimport * as z from \"zod\";\nimport { createBillingStore } from \"./billing-store.ts\";\nimport type { FlutterwaveTransactionData } from \"./flutterwave-contracts.ts\";\nimport { createFlutterwaveAdapter } from \"./flutterwave-sdk.ts\";\nimport { parseFlutterwaveMetadata } from \"./metadata.ts\";\nimport { acquireOperation, checkpointOperation, failOperation } from \"./operation-ledger.ts\";\nimport { encryptPaymentToken } from \"./token-crypto.ts\";\nimport type {\n AnyFlutterwaveOptions,\n FlutterwaveTransaction,\n FlutterwaveWebhookEvent,\n} from \"./types.ts\";\nimport { getNextPeriodEnd, getPlans, normalizeSubscriptionGroup } from \"./utils.ts\";\n\nconst fulfillmentSchema = z.object({\n initialCompletion: z.boolean(),\n completed: z.array(z.enum([\"complete\", \"created\", \"update\"])),\n});\n\nexport function paymentMatches(\n expected: FlutterwaveTransaction,\n verified: FlutterwaveTransactionData,\n): boolean {\n return (\n verified.tx_ref === expected.txRef &&\n verified.amount === expected.amount &&\n verified.currency === expected.currency\n );\n}\n\n/** Shared fulfillment for browser verification, webhooks, and trusted reconciliation. */\nexport async function recordVerifiedPayment(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n expected: FlutterwaveTransaction,\n verified: FlutterwaveTransactionData,\n webhookEvent?: FlutterwaveWebhookEvent,\n): Promise<void> {\n if (!paymentMatches(expected, verified)) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Verified transaction does not match the expected payment\",\n });\n }\n const store = createBillingStore(ctx);\n const now = new Date();\n // A late pending/failed notification must not undo an already verified payment.\n if (expected.status === \"successful\" && verified.status !== \"successful\") return;\n await store.updateTransactionByTxRef(expected.txRef, {\n transactionId: verified.id,\n flwRef: verified.flw_ref,\n chargedAmount: verified.charged_amount,\n paymentType: verified.payment_type,\n status: verified.status,\n verifiedAt: expected.verifiedAt ?? now,\n reconciledAt: now,\n updatedAt: now,\n });\n if (verified.status !== \"successful\" || options.subscription?.enabled !== true) return;\n\n for (const subscription of await store.findSubscriptionsByTxRef(expected.txRef)) {\n if (subscription.status === \"canceled\" || subscription.endedAt != null) continue;\n const group = normalizeSubscriptionGroup(subscription.groupId);\n const siblings = await store.findSubscriptionsByReference(subscription.referenceId);\n const superseded = siblings.some(\n (candidate) =>\n candidate.id !== subscription.id &&\n normalizeSubscriptionGroup(candidate.groupId) === group &&\n (candidate.status === \"active\" ||\n candidate.status === \"trialing\" ||\n (candidate.status === \"canceled\" && candidate.periodStart != null)) &&\n new Date(candidate.createdAt).getTime() > new Date(subscription.createdAt).getTime(),\n );\n if (superseded) {\n await store.updateSubscription(subscription.id, {\n status: \"canceled\",\n canceledAt: now,\n endedAt: now,\n updatedAt: now,\n });\n continue;\n }\n\n let subscriptionId = subscription.subscriptionId;\n if (\n subscription.paymentPlanId != null &&\n subscriptionId == null &&\n subscription.billingEmail != null &&\n subscription.billingEmail !== \"\"\n ) {\n const provider = createFlutterwaveAdapter(options);\n const remote = await provider.listSubscriptions({\n email: subscription.billingEmail,\n plan: subscription.paymentPlanId,\n transactionId: verified.id,\n });\n const candidates = remote.filter((candidate) => candidate.status !== \"cancelled\");\n subscriptionId = candidates.length === 1 ? candidates[0]?.id : undefined;\n }\n const identified = subscription.paymentPlanId == null || subscriptionId != null;\n const paidAt =\n verified.created_at != null && verified.created_at !== \"\"\n ? new Date(verified.created_at)\n : now;\n const paymentTime = Number.isFinite(paidAt.getTime()) ? paidAt : now;\n const renewal = parseFlutterwaveMetadata(expected.metadata).type === \"renewal\";\n const priorEnd = subscription.periodEnd ? new Date(subscription.periodEnd) : null;\n const periodStart =\n renewal && priorEnd !== null && priorEnd > paymentTime ? priorEnd : paymentTime;\n // Renewal operations set past_due before fulfillment. This survives a failure after\n // recording payment, while the conditional status update prevents concurrent retries\n // from advancing a period that another worker has already fulfilled.\n const advancePeriod =\n subscription.periodEnd == null ||\n (renewal ? subscription.status === \"past_due\" : expected.status !== \"successful\");\n const update = {\n subscriptionId,\n status: identified ? \"active\" : \"incomplete\",\n encryptedPaymentToken:\n verified.card?.token !== undefined\n ? await encryptPaymentToken(verified.card.token, ctx.context.secret)\n : subscription.encryptedPaymentToken,\n ...(advancePeriod\n ? {\n periodStart,\n periodEnd: getNextPeriodEnd(periodStart, subscription.billingInterval ?? \"monthly\"),\n }\n : {}),\n reconciledAt: now,\n updatedAt: now,\n };\n if (!identified) {\n await store.updateCurrentSubscription(subscription, update);\n continue;\n }\n let operation = await acquireOperation(store, {\n eventId: `internal:payment:${verified.id}:${subscription.id}`,\n eventType: \"internal.payment.fulfillment\",\n txRef: expected.txRef,\n payload: JSON.stringify({\n initialCompletion: subscription.status === \"incomplete\",\n completed: [],\n }),\n });\n if (operation.status === \"processed\") continue;\n try {\n const progress = fulfillmentSchema.parse(JSON.parse(operation.payload));\n // The ledger retains initial-completion intent even if a prior worker already activated the row.\n const updated = await store.updateCurrentSubscription(subscription, update);\n if (!updated) {\n operation = await checkpointOperation(store, operation, {\n status: \"processed\",\n processedAt: new Date(),\n });\n continue;\n }\n const plan = (await getPlans(options.subscription)).find(\n (candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase(),\n );\n if (plan) {\n const callbackEvent: FlutterwaveWebhookEvent = webhookEvent ?? {\n event: \"charge.completed\",\n data: {\n id: verified.id,\n tx_ref: verified.tx_ref,\n ...(verified.flw_ref !== undefined &&\n verified.flw_ref !== null &&\n verified.flw_ref !== \"\"\n ? { flw_ref: verified.flw_ref }\n : {}),\n status: verified.status,\n amount: verified.amount,\n currency: verified.currency,\n },\n };\n const currentSubscription = { ...subscription, ...update };\n const callbackData = { event: callbackEvent, subscription: currentSubscription, plan };\n const callbacks = [\n {\n key: \"complete\" as const,\n callback: progress.initialCompletion\n ? options.subscription?.onSubscriptionComplete\n : undefined,\n },\n {\n key: \"created\" as const,\n callback: progress.initialCompletion\n ? options.subscription?.onSubscriptionCreated\n : undefined,\n },\n { key: \"update\" as const, callback: options.subscription?.onSubscriptionUpdate },\n ];\n for (const { key, callback } of callbacks) {\n if (progress.completed.includes(key)) continue;\n // Refresh the lease before external work; handlers must still tolerate at-least-once delivery.\n operation = await checkpointOperation(store, operation, {});\n await callback?.(callbackData, ctx);\n progress.completed.push(key);\n operation = await checkpointOperation(store, operation, {\n payload: JSON.stringify(progress),\n });\n }\n }\n await store.retireCompetingSubscriptions(subscription.referenceId, group, subscription.id);\n operation = await checkpointOperation(store, operation, {\n status: \"processed\",\n processedAt: new Date(),\n });\n } catch (error) {\n await failOperation(store, operation);\n throw error;\n }\n }\n}\n","import type { GenericEndpointContext } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\n\nimport type { AnyFlutterwaveOptions, Session, User } from \"./types.ts\";\n\nexport type BillingReferenceAction =\n | \"initialize-transaction\"\n | \"verify-transaction\"\n | \"list-subscriptions\"\n | \"list-transactions\"\n | \"disable-subscription\"\n | \"enable-subscription\"\n | \"get-subscription-manage-link\";\n\nconst DEFAULT_BILLING_ORG_ROLES = [\"owner\", \"admin\"] as const;\n\nfunction normalizeBillingRoles(roles: readonly string[]): Set<string> {\n return new Set(roles.map((value) => value.trim()).filter((value) => value !== \"\"));\n}\n\nexport function getBillingRoles(options: AnyFlutterwaveOptions): readonly string[] {\n return options.organization?.billingRoles ?? DEFAULT_BILLING_ORG_ROLES;\n}\n\nexport function hasBillingRole(\n role: unknown,\n billingRoles: readonly string[] = DEFAULT_BILLING_ORG_ROLES,\n): boolean {\n const allowedRoles = normalizeBillingRoles(billingRoles);\n if (Array.isArray(role)) {\n return role.some((value) => hasBillingRole(value, billingRoles));\n }\n if (typeof role !== \"string\") {\n return false;\n }\n return role\n .split(\",\")\n .map((value) => value.trim())\n .some((value) => allowedRoles.has(value));\n}\n\nexport function resolveBillingReferenceId(input: {\n body?: unknown;\n query?: unknown;\n requestUrl?: string;\n fallbackUserId: string;\n}): string {\n const body = (input.body ?? {}) as Record<string, unknown>;\n const query = (input.query ?? {}) as Record<string, unknown>;\n const requestQueryReferenceId =\n typeof input.requestUrl === \"string\"\n ? (new URL(input.requestUrl).searchParams.get(\"referenceId\") ?? undefined)\n : undefined;\n\n return (\n (body.referenceId as string | undefined) ??\n (query.referenceId as string | undefined) ??\n requestQueryReferenceId ??\n input.fallbackUserId\n );\n}\n\nexport async function authorizeBillingReference(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n data: {\n user: User;\n session: Session;\n referenceId: string;\n action: BillingReferenceAction;\n },\n): Promise<void> {\n if (data.referenceId === data.user.id) return;\n\n if (\n options.subscription?.enabled === true &&\n typeof options.subscription.authorizeReference === \"function\"\n ) {\n const authorized = await options.subscription.authorizeReference(\n {\n user: data.user,\n session: data.session,\n referenceId: data.referenceId,\n action: data.action,\n },\n ctx,\n );\n if (authorized === true) return;\n throw new APIError(\"UNAUTHORIZED\");\n }\n\n if (options.organization?.enabled === true) {\n const member = await ctx.context.adapter.findOne({\n model: \"member\",\n where: [\n { field: \"userId\", value: data.user.id },\n { field: \"organizationId\", value: data.referenceId },\n ],\n });\n\n if (\n member !== null &&\n member !== undefined &&\n hasBillingRole((member as { role?: unknown }).role, getBillingRoles(options))\n ) {\n return;\n }\n }\n\n throw new APIError(\"UNAUTHORIZED\");\n}\n","import type { GenericEndpointContext } from \"better-auth\";\n\nexport function getWebhookRequest(ctx: GenericEndpointContext): Request | undefined {\n return (\n (ctx as unknown as { requestClone?: Request }).requestClone ??\n (ctx as { request?: Request }).request\n );\n}\n\nexport function getWebhookHeaders(ctx: GenericEndpointContext): Headers | undefined {\n return (\n (ctx as GenericEndpointContext & { headers?: Headers }).headers ??\n (ctx.request as unknown as { headers?: Headers })?.headers\n );\n}\n\nexport function getWebhookClientIP(\n ctx: GenericEndpointContext,\n headers: Headers | undefined,\n): string | undefined {\n return (\n headers?.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n headers?.get(\"x-real-ip\") ??\n (ctx.request as unknown as { ip?: string }).ip\n );\n}\n","import { defineErrorCodes } from \"better-auth\";\nimport type { RawError } from \"better-auth\";\nimport { timingSafeEqual } from \"node:crypto\";\nimport { Buffer as NodeBuffer } from \"node:buffer\";\n\nimport type { AnyFlutterwaveOptions, FlutterwaveCheckoutChannel } from \"../types.ts\";\n\nexport const FLUTTERWAVE_ERROR_CODES: {\n SUBSCRIPTION_NOT_FOUND: RawError<\"SUBSCRIPTION_NOT_FOUND\">;\n SUBSCRIPTION_PLAN_NOT_FOUND: RawError<\"SUBSCRIPTION_PLAN_NOT_FOUND\">;\n FAILED_TO_INITIALIZE_TRANSACTION: RawError<\"FAILED_TO_INITIALIZE_TRANSACTION\">;\n FAILED_TO_VERIFY_TRANSACTION: RawError<\"FAILED_TO_VERIFY_TRANSACTION\">;\n FAILED_TO_DISABLE_SUBSCRIPTION: RawError<\"FAILED_TO_DISABLE_SUBSCRIPTION\">;\n FAILED_TO_ENABLE_SUBSCRIPTION: RawError<\"FAILED_TO_ENABLE_SUBSCRIPTION\">;\n EMAIL_VERIFICATION_REQUIRED: RawError<\"EMAIL_VERIFICATION_REQUIRED\">;\n SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED: RawError<\"SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED\">;\n} = defineErrorCodes({\n SUBSCRIPTION_NOT_FOUND: \"Subscription not found\",\n SUBSCRIPTION_PLAN_NOT_FOUND: \"Subscription plan not found\",\n FAILED_TO_INITIALIZE_TRANSACTION: \"Failed to initialize transaction\",\n FAILED_TO_VERIFY_TRANSACTION: \"Failed to verify transaction\",\n FAILED_TO_DISABLE_SUBSCRIPTION: \"Failed to disable subscription\",\n FAILED_TO_ENABLE_SUBSCRIPTION: \"Failed to enable subscription\",\n EMAIL_VERIFICATION_REQUIRED: \"Email verification is required before you can subscribe to a plan\",\n SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED:\n \"This subscription only supports specific payment channels\",\n});\n\nexport function getAllowedSubscriptionChannels(\n options: AnyFlutterwaveOptions,\n): FlutterwaveCheckoutChannel[] | undefined {\n const channels = options.subscription?.allowedPaymentChannels;\n return Array.isArray(channels) && channels.length > 0 ? channels : undefined;\n}\n\nexport async function hmacSha256Base64(secret: string, message: string): Promise<string> {\n const encoder = new TextEncoder();\n const keyData = encoder.encode(secret);\n const msgData = encoder.encode(message);\n\n const crypto = globalThis.crypto;\n if (crypto !== undefined && crypto !== null && \"subtle\" in crypto) {\n const subtle = crypto.subtle;\n const key = await subtle.importKey(\"raw\", keyData, { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n ]);\n const signature = await subtle.sign(\"HMAC\", key, msgData);\n return NodeBuffer.from(signature).toString(\"base64\");\n }\n\n const { createHmac } = await import(\"node:crypto\");\n return createHmac(\"sha256\", secret).update(message).digest(\"base64\");\n}\n\nexport function timingSafeEqualString(left: string, right: string): boolean {\n const leftBytes = NodeBuffer.from(left);\n const rightBytes = NodeBuffer.from(right);\n if (leftBytes.length !== rightBytes.length) return false;\n return timingSafeEqual(leftBytes, rightBytes);\n}\n","/* oxlint-disable no-restricted-imports, typescript/strict-boolean-expressions */\nimport { createHash } from \"node:crypto\";\nimport { HIDE_METADATA } from \"better-auth\";\nimport type { GenericEndpointContext } from \"better-auth\";\nimport {\n APIError,\n getSessionFromCtx,\n originCheckMiddleware,\n sessionMiddleware,\n} from \"better-auth/api\";\nimport { createAuthEndpoint } from \"better-auth/api\";\nimport * as z from \"zod\";\nimport { createBillingStore } from \"./billing-store.ts\";\nimport { paymentMatches, recordVerifiedPayment } from \"./billing-lifecycle.ts\";\nimport type { FlutterwaveTransactionData } from \"./flutterwave-contracts.ts\";\nimport { createFlutterwaveAdapter } from \"./flutterwave-sdk.ts\";\nimport { createCheckoutMetadata, stringifyFlutterwaveMetadata } from \"./metadata.ts\";\nimport { authorizeBillingReference, resolveBillingReferenceId } from \"./reference-access.ts\";\nimport { getWebhookHeaders, getWebhookRequest } from \"./route-modules/webhook.ts\";\nimport {\n FLUTTERWAVE_ERROR_CODES,\n hmacSha256Base64,\n timingSafeEqualString,\n} from \"./route-modules/shared.ts\";\nimport type {\n AnyFlutterwaveOptions,\n FlutterwaveInitializeResult,\n FlutterwaveProduct,\n FlutterwaveTransactionResponse,\n FlutterwaveV4WebhookEvent,\n FlutterwaveWebhookEvent,\n Session,\n User,\n} from \"./types.ts\";\nimport {\n calculatePlanAmount,\n getPlanSeatAmount,\n getPlans,\n normalizeSubscriptionGroup,\n} from \"./utils.ts\";\n\nexport { FLUTTERWAVE_ERROR_CODES };\n\nconst subaccountSchema = z.object({\n id: z.string().min(1),\n transactionSplitRatio: z.number().positive().optional(),\n transactionChargeType: z.enum([\"flat\", \"percentage\", \"flat_subaccount\"]).optional(),\n transactionCharge: z.number().nonnegative().optional(),\n});\n\nconst initializeBodySchema = z.object({\n amount: z.number().positive().optional(),\n currency: z\n .string()\n .length(3)\n .transform((value) => value.toUpperCase())\n .optional(),\n redirectUrl: z.string().url(),\n txRef: z.string().min(1).max(100).optional(),\n referenceId: z.string().optional(),\n plan: z.string().optional(),\n product: z.string().optional(),\n quantity: z.number().int().positive().default(1),\n metadata: z.record(z.string(), z.unknown()).optional(),\n paymentOptions: z.string().optional(),\n subaccounts: z.array(subaccountSchema).optional(),\n});\n\nconst verifyBodySchema = z\n .object({\n transactionId: z.union([z.string(), z.number()]).optional(),\n txRef: z.string().optional(),\n referenceId: z.string().optional(),\n })\n .refine((body) => (body.transactionId === undefined) !== (body.txRef === undefined), {\n message: \"Provide exactly one of transactionId or txRef\",\n });\n\nconst v3WebhookPayloadSchema = z.object({\n event: z.string().min(1),\n data: z\n .object({\n id: z.union([z.string(), z.number()]).optional(),\n tx_ref: z.string().optional(),\n flw_ref: z.string().optional(),\n status: z.string().optional(),\n amount: z.coerce.number().optional(),\n charged_amount: z.coerce.number().optional(),\n currency: z.string().optional(),\n payment_type: z.string().optional(),\n customer: z.object({ email: z.string().optional() }).passthrough().optional(),\n plan: z\n .object({ id: z.union([z.string(), z.number()]).optional() })\n .passthrough()\n .optional(),\n })\n .passthrough(),\n});\n\nconst v4WebhookPayloadSchema = z.object({\n type: z.string().min(1),\n id: z.string().optional(),\n webhook_id: z.string().optional(),\n timestamp: z.union([z.string(), z.number()]).optional(),\n data: z\n .object({\n id: z.string().optional(),\n reference: z.string().optional(),\n status: z.string().optional(),\n amount: z.coerce.number().optional(),\n currency: z.string().optional(),\n customer: z\n .object({ id: z.string().optional(), email: z.string().optional() })\n .passthrough()\n .optional(),\n })\n .passthrough(),\n});\n\nfunction adapter(options: AnyFlutterwaveOptions) {\n return createFlutterwaveAdapter({\n publicKey: options.publicKey,\n secretKey: options.secretKey,\n flutterwaveClient: options.flutterwaveClient,\n fetch: options.fetch,\n apiBaseUrl: options.apiBaseUrl,\n });\n}\n\nfunction mapTransaction(data: FlutterwaveTransactionData): FlutterwaveTransactionResponse {\n return {\n id: data.id,\n txRef: data.tx_ref,\n flwRef: data.flw_ref ?? undefined,\n status: data.status,\n amount: data.amount,\n chargedAmount: data.charged_amount,\n currency: data.currency,\n paymentType: data.payment_type ?? undefined,\n customer: data.customer\n ? {\n email: data.customer.email,\n name: data.customer.name ?? undefined,\n }\n : undefined,\n };\n}\n\nasync function authenticatedReference(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n action:\n | \"initialize-transaction\"\n | \"verify-transaction\"\n | \"list-subscriptions\"\n | \"list-transactions\"\n | \"disable-subscription\"\n | \"enable-subscription\",\n requested?: string,\n): Promise<{ user: User; session: Session; referenceId: string }> {\n const current = await getSessionFromCtx(ctx);\n if (!current) throw new APIError(\"UNAUTHORIZED\");\n const referenceId = requested ?? current.user.id;\n await authorizeBillingReference(ctx, options, {\n user: current.user,\n session: current.session,\n referenceId,\n action,\n });\n return { user: current.user, session: current.session, referenceId };\n}\n\nasync function resolveBillingEmail(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n referenceId: string,\n user: User,\n): Promise<string> {\n if (referenceId === user.id) return user.email;\n if (options.organization?.enabled !== true) throw new APIError(\"UNAUTHORIZED\");\n const store = createBillingStore(ctx);\n const organization = await store.findOrganization(referenceId);\n const explicit = (organization as { email?: string | null } | null)?.email;\n if (explicit) return explicit;\n const owner = await store.findOrganizationOwner(referenceId);\n const ownerUser = owner ? await store.findUser(owner.userId) : null;\n if (!ownerUser?.email) throw new APIError(\"BAD_REQUEST\", { message: \"Billing email not found\" });\n return ownerUser.email;\n}\n\nasync function configuredProducts(options: AnyFlutterwaveOptions): Promise<FlutterwaveProduct[]> {\n const source = options.products?.products;\n if (!source) return [];\n return typeof source === \"function\" ? source() : source;\n}\n\nexport const initializeTransaction = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n {\n method: \"POST\",\n body: initializeBodySchema,\n use: [sessionMiddleware, originCheckMiddleware],\n },\n async (ctx) => {\n const { user, referenceId } = await authenticatedReference(\n ctx,\n options,\n \"initialize-transaction\",\n ctx.body.referenceId,\n );\n if (\n options.subscription?.requireEmailVerification === true &&\n ctx.body.plan &&\n user.emailVerified !== true\n ) {\n throw new APIError(\"BAD_REQUEST\", FLUTTERWAVE_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED);\n }\n\n const billingEmail = await resolveBillingEmail(ctx, options, referenceId, user);\n const plans = await getPlans(options.subscription);\n const plan = ctx.body.plan\n ? plans.find((candidate) => candidate.name.toLowerCase() === ctx.body.plan?.toLowerCase())\n : undefined;\n if (ctx.body.plan && !plan) throw new APIError(\"NOT_FOUND\", { message: \"Plan not found\" });\n\n const products = await configuredProducts(options);\n const product = ctx.body.product\n ? products.find(\n (candidate) =>\n candidate.name.toLowerCase() === ctx.body.product?.toLowerCase() ||\n candidate.slug === ctx.body.product,\n )\n : undefined;\n if (ctx.body.product && !product) {\n throw new APIError(\"NOT_FOUND\", { message: \"Product not found\" });\n }\n if (plan && product) {\n throw new APIError(\"BAD_REQUEST\", { message: \"Select a plan or a product, not both\" });\n }\n if (plan) {\n if (plan.freeTrial?.days !== undefined && plan.freeTrial.days > 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message:\n \"Flutterwave v3 checkout cannot start a no-charge trial. Do not configure freeTrial until a customer-visible tokenization charge and local trial lifecycle are implemented.\",\n });\n }\n if (plan.amount === undefined || !Number.isFinite(plan.amount) || plan.amount <= 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The plan requires a configured positive amount\",\n });\n }\n if (\n ctx.body.quantity > 1 &&\n (plan.paymentPlanId != null || getPlanSeatAmount(plan) === undefined)\n ) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Additional seats require a locally billed per-seat price\",\n });\n }\n }\n\n const amount = plan\n ? calculatePlanAmount(plan, ctx.body.quantity)\n : product\n ? product.price * ctx.body.quantity\n : ctx.body.amount;\n const currency = plan ? plan.currency : product ? product.currency : ctx.body.currency;\n if (!amount || !currency) {\n throw new APIError(\"BAD_REQUEST\", { message: \"amount and currency are required\" });\n }\n\n const requestedSplits = ctx.body.subaccounts ?? options.marketplace?.defaultSplit;\n const allowed = new Set(options.marketplace?.allowedSubaccountIds ?? []);\n if (requestedSplits?.some(({ id }) => !allowed.has(id))) {\n throw new APIError(\"FORBIDDEN\", { message: \"Subaccount is not allowlisted\" });\n }\n const txRef = ctx.body.txRef ?? `flw_${crypto.randomUUID()}`;\n const groupId = normalizeSubscriptionGroup(plan?.group);\n const metadata = createCheckoutMetadata({\n referenceId,\n userId: user.id,\n plan: plan?.name,\n groupId,\n product: product?.name,\n extra: ctx.body.metadata,\n trial: { isTrial: false, requested: false, granted: false },\n });\n const result = await adapter(options).initializePayment({\n tx_ref: txRef,\n amount,\n currency,\n redirect_url: ctx.body.redirectUrl,\n customer: { email: billingEmail, name: user.name },\n payment_options: plan?.paymentPlanId ? \"card\" : ctx.body.paymentOptions,\n payment_plan: plan?.paymentPlanId,\n subaccounts: requestedSplits?.map((split) => ({\n id: split.id,\n transaction_charge_type:\n split.transactionChargeType === \"flat_subaccount\"\n ? \"flat\"\n : split.transactionChargeType,\n transaction_charge: split.transactionCharge,\n transaction_split_ratio: split.transactionSplitRatio,\n })),\n meta: metadata,\n });\n\n const store = createBillingStore(ctx);\n const now = new Date();\n await store.createTransaction({\n txRef,\n referenceId,\n userId: user.id,\n amount,\n currency,\n status: \"pending\",\n plan: plan?.name,\n product: product?.name,\n subaccountId: requestedSplits?.[0]?.id,\n metadata: stringifyFlutterwaveMetadata(metadata),\n createdAt: now,\n updatedAt: now,\n });\n if (plan) {\n await store.createSubscription({\n userId: user.id,\n referenceId,\n plan: plan.name,\n paymentPlanId: plan.paymentPlanId,\n txRef,\n billingEmail,\n status: \"incomplete\",\n seats: ctx.body.quantity,\n groupId,\n cancelAtPeriodEnd: false,\n billingInterval: plan.interval,\n createdAt: now,\n updatedAt: now,\n });\n }\n return {\n kind: \"checkout\",\n url: result.link,\n txRef,\n redirect: true,\n } satisfies FlutterwaveInitializeResult;\n },\n );\n\nexport const verifyTransaction = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n { method: \"POST\", body: verifyBodySchema, use: [sessionMiddleware, originCheckMiddleware] },\n async (ctx) => {\n const store = createBillingStore(ctx);\n const verified = await adapter(options).verifyTransaction({\n transactionId:\n ctx.body.transactionId === undefined ? undefined : Number(ctx.body.transactionId),\n txRef: ctx.body.txRef,\n });\n const expected = await store.findTransactionByTxRef(verified.tx_ref);\n if (!expected) throw new APIError(\"NOT_FOUND\", { message: \"Transaction not found\" });\n if (ctx.body.referenceId !== undefined && ctx.body.referenceId !== expected.referenceId) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n await authenticatedReference(ctx, options, \"verify-transaction\", expected.referenceId);\n if (\n (ctx.body.txRef !== undefined && verified.tx_ref !== ctx.body.txRef) ||\n !paymentMatches(expected, verified) ||\n verified.status !== \"successful\"\n ) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Verified transaction does not match the expected payment\",\n });\n }\n await recordVerifiedPayment(ctx, options, expected, verified);\n return {\n status: verified.status,\n txRef: verified.tx_ref,\n data: mapTransaction(verified),\n };\n },\n );\n\nconst referenceQuerySchema = z.object({ referenceId: z.string().optional() });\n\nexport const listTransactions = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n { method: \"GET\", query: referenceQuerySchema, use: [sessionMiddleware] },\n async (ctx) => {\n const current = await getSessionFromCtx(ctx);\n if (!current) throw new APIError(\"UNAUTHORIZED\");\n const referenceId = resolveBillingReferenceId({\n query: ctx.query,\n requestUrl: ctx.request?.url,\n fallbackUserId: current.user.id,\n });\n await authenticatedReference(ctx, options, \"list-transactions\", referenceId);\n return { transactions: await createBillingStore(ctx).listTransactions(referenceId) };\n },\n );\n\nexport const listSubscriptions = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n { method: \"GET\", query: referenceQuerySchema, use: [sessionMiddleware] },\n async (ctx) => {\n const current = await getSessionFromCtx(ctx);\n if (!current) throw new APIError(\"UNAUTHORIZED\");\n const referenceId = resolveBillingReferenceId({\n query: ctx.query,\n requestUrl: ctx.request?.url,\n fallbackUserId: current.user.id,\n });\n await authenticatedReference(ctx, options, \"list-subscriptions\", referenceId);\n return {\n subscriptions: await createBillingStore(ctx).findSubscriptionsByReference(referenceId),\n };\n },\n );\n\nconst subscriptionBodySchema = z.object({\n subscriptionId: z.union([z.number().int().positive(), z.string().min(1)]),\n atPeriodEnd: z.boolean().optional(),\n});\n\nasync function findSubscription(ctx: GenericEndpointContext, id: string | number) {\n const store = createBillingStore(ctx);\n if (typeof id === \"string\") {\n const local = await store.findSubscriptionById(id);\n if (local) return local;\n }\n const providerId = Number(id);\n return Number.isInteger(providerId) && providerId > 0\n ? store.findSubscriptionByProviderId(providerId)\n : null;\n}\n\nexport const cancelSubscription = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n {\n method: \"POST\",\n body: subscriptionBodySchema,\n use: [sessionMiddleware, originCheckMiddleware],\n },\n async (ctx) => {\n const store = createBillingStore(ctx);\n const local = await findSubscription(ctx, ctx.body.subscriptionId);\n if (!local) throw new APIError(\"NOT_FOUND\", { message: \"Subscription not found\" });\n await authenticatedReference(ctx, options, \"disable-subscription\", local.referenceId);\n const now = new Date();\n if (\n ctx.body.atPeriodEnd === true ||\n options.subscription?.cancelBehavior === \"at_period_end\"\n ) {\n if (!local.periodEnd || !Number.isFinite(new Date(local.periodEnd).getTime())) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The paid subscription period is unknown; cancel immediately instead\",\n });\n }\n if (local.paymentPlanId != null && local.subscriptionId == null) {\n throw new APIError(\"BAD_REQUEST\", {\n message:\n \"The native subscription has not been identified yet; reconcile its payment first\",\n });\n }\n // Stop the next provider charge now; the scheduler ends the already-paid access later.\n if (local.subscriptionId != null && local.cancelAtPeriodEnd !== true) {\n await adapter(options).cancelSubscription(local.subscriptionId);\n }\n await store.updateSubscription(local.id, {\n cancelAtPeriodEnd: true,\n cancelAt: local.periodEnd,\n ...(local.subscriptionId != null ? { canceledAt: local.canceledAt ?? now } : {}),\n updatedAt: now,\n });\n return { status: \"scheduled\" };\n }\n if (local.paymentPlanId != null && local.subscriptionId == null) {\n throw new APIError(\"BAD_REQUEST\", {\n message:\n \"The native subscription has not been identified yet; reconcile its payment first\",\n });\n }\n if (local.subscriptionId != null)\n await adapter(options).cancelSubscription(local.subscriptionId);\n const canceled = await store.updateSubscription(local.id, {\n status: \"canceled\",\n cancelAtPeriodEnd: false,\n canceledAt: now,\n endedAt: now,\n updatedAt: now,\n });\n if (canceled) {\n const plan = await getPlans(options.subscription).then((plans) =>\n plans.find((candidate) => candidate.name.toLowerCase() === local.plan.toLowerCase()),\n );\n if (plan) {\n const callbackData = {\n event: { event: \"subscription.cancelled\", data: {} },\n subscription: canceled,\n };\n await options.subscription?.onSubscriptionCancel?.(\n callbackData,\n ctx as GenericEndpointContext,\n );\n await options.subscription?.onSubscriptionUpdate?.(\n { ...callbackData, plan },\n ctx as GenericEndpointContext,\n );\n }\n }\n return { status: \"canceled\" };\n },\n );\n\nexport const restoreSubscription = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n {\n method: \"POST\",\n body: subscriptionBodySchema.omit({ atPeriodEnd: true }),\n use: [sessionMiddleware, originCheckMiddleware],\n },\n async (ctx) => {\n const store = createBillingStore(ctx);\n const local = await findSubscription(ctx, ctx.body.subscriptionId);\n if (!local) throw new APIError(\"NOT_FOUND\", { message: \"Subscription not found\" });\n await authenticatedReference(ctx, options, \"enable-subscription\", local.referenceId);\n if (\n local.subscriptionId == null &&\n local.periodEnd != null &&\n new Date(local.periodEnd) <= new Date()\n ) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The paid period has ended; renew through checkout instead\",\n });\n }\n if (local.cancelAtPeriodEnd !== true || local.canceledAt != null) {\n if (local.subscriptionId == null) {\n if (local.status === \"active\" && local.endedAt == null) return { status: \"active\" };\n throw new APIError(\"BAD_REQUEST\", {\n message: \"A canceled local subscription requires a new checkout\",\n });\n }\n await adapter(options).activateSubscription(local.subscriptionId);\n }\n await store.updateSubscription(local.id, {\n status: local.cancelAtPeriodEnd === true ? local.status : \"active\",\n cancelAtPeriodEnd: false,\n cancelAt: null,\n canceledAt: null,\n endedAt: null,\n updatedAt: new Date(),\n });\n return { status: local.cancelAtPeriodEnd === true ? local.status : \"active\" };\n },\n );\n\nexport const createSubscription = initializeTransaction;\nexport const upgradeSubscription = initializeTransaction;\nexport const disableFlutterwaveSubscription = cancelSubscription;\nexport const enableFlutterwaveSubscription = restoreSubscription;\n\nexport const listProducts = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(path, { method: \"GET\" }, async (ctx) => {\n const configured = await configuredProducts(options);\n const stored = await createBillingStore(ctx).listProducts();\n return { products: stored.length > 0 ? stored : configured };\n });\n\nexport const listPlans = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(path, { method: \"GET\" }, async (ctx) => {\n const configured = await getPlans(options.subscription);\n const stored = await createBillingStore(ctx).listPlans();\n return { plans: stored.length > 0 ? stored : configured };\n });\n\nexport const getConfig = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(path, { method: \"GET\" }, async (ctx) => ({\n plans: (await createBillingStore(ctx).listPlans()).concat(await getPlans(options.subscription)),\n products: await configuredProducts(options),\n subscriptions: options.subscription?.enabled === true,\n marketplace: options.marketplace !== undefined,\n }));\n\nexport const flutterwaveWebhook = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n {\n method: \"POST\",\n metadata: { ...HIDE_METADATA, openapi: { operationId: \"flutterwaveWebhook\" } },\n cloneRequest: true,\n disableBody: true,\n },\n async (ctx) => {\n const request = getWebhookRequest(ctx as GenericEndpointContext);\n if (!request) throw new APIError(\"BAD_REQUEST\", { message: \"Request is missing\" });\n const rawBody = await request.text();\n const headers = getWebhookHeaders(ctx as GenericEndpointContext);\n const signature = headers?.get(\"flutterwave-signature\");\n const legacyHash = headers?.get(\"verif-hash\");\n const secretHash = options.webhook?.secretHash ?? options.secretHash;\n if (typeof signature !== \"string\" && typeof legacyHash !== \"string\") {\n throw new APIError(\"UNAUTHORIZED\", { message: \"Missing signature\" });\n }\n const validV4Signature =\n typeof signature === \"string\" &&\n timingSafeEqualString(signature, await hmacSha256Base64(secretHash, rawBody));\n const validV3Hash =\n typeof legacyHash === \"string\" && timingSafeEqualString(legacyHash, secretHash);\n if (!validV4Signature && !validV3Hash) {\n throw new APIError(\"UNAUTHORIZED\", { message: \"Invalid signature\" });\n }\n\n let webhookJson: unknown;\n try {\n webhookJson = JSON.parse(rawBody);\n } catch {\n ctx.context.logger.warn(\"Ignoring non-JSON signed Flutterwave webhook\");\n return ctx.json({ received: true });\n }\n const parsedV3 = v3WebhookPayloadSchema.safeParse(webhookJson);\n const parsedV4 = parsedV3.success ? undefined : v4WebhookPayloadSchema.safeParse(webhookJson);\n if (!parsedV3.success && !parsedV4?.success) {\n ctx.context.logger.warn(\"Ignoring malformed signed Flutterwave webhook\");\n return ctx.json({ received: true });\n }\n let event: FlutterwaveWebhookEvent | FlutterwaveV4WebhookEvent;\n if (parsedV3.success) event = parsedV3.data;\n else if (parsedV4?.success) event = parsedV4.data;\n else throw new APIError(\"BAD_REQUEST\", { message: \"Malformed webhook\" });\n\n const providerEventId = \"type\" in event ? (event.webhook_id ?? event.id) : undefined;\n const eventId =\n providerEventId ??\n createHash(\"sha256\")\n .update(\n \"type\" in event\n ? rawBody\n : event.data.id === undefined\n ? rawBody\n : `${event.event}:${String(event.data.id)}:${String(event.data.status ?? \"\")}`,\n )\n .digest(\"hex\");\n const eventType = \"type\" in event ? event.type : event.event;\n const txRef = \"type\" in event ? event.data.reference : event.data.tx_ref;\n const providerTransactionId = \"type\" in event ? undefined : event.data.id;\n const store = createBillingStore(ctx);\n const existingEvent = await store.findWebhookEvent(eventId);\n if (existingEvent?.status === \"processed\") return ctx.json({ received: true });\n const now = new Date();\n const busy = () =>\n new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"Webhook processing is still in progress; retry delivery\",\n });\n if (existingEvent === null) {\n try {\n await store.createWebhookEvent({\n eventId,\n eventType,\n transactionId:\n providerTransactionId !== undefined &&\n Number.isSafeInteger(Number(providerTransactionId))\n ? Number(providerTransactionId)\n : undefined,\n txRef,\n payload: rawBody,\n status: \"processing\",\n createdAt: now,\n updatedAt: now,\n });\n } catch (error) {\n const concurrent = await store.findWebhookEvent(eventId);\n if (concurrent === null) throw error;\n if (concurrent.status === \"processed\") {\n return ctx.json({ received: true });\n }\n throw busy();\n }\n } else {\n const leaseExpiresAt = new Date(existingEvent.updatedAt).getTime() + 5 * 60_000;\n if (existingEvent.status === \"processing\" && leaseExpiresAt > now.getTime()) throw busy();\n if (!(await store.claimWebhookEvent(existingEvent, now))) throw busy();\n }\n\n try {\n const v3TransactionRef = \"event\" in event ? event.data.tx_ref : undefined;\n if (v3TransactionRef && \"event\" in event && event.data.id !== undefined) {\n const data = event.data;\n const local = await store.findTransactionByTxRef(v3TransactionRef);\n if (!local) throw new Error(\"The webhook payment has not been recorded locally yet\");\n const verified = await adapter(options).verifyTransaction({\n transactionId: Number(data.id),\n });\n if (data.status === \"successful\" && verified.status !== \"successful\") {\n throw new Error(\"The provider has not verified the successful payment yet\");\n }\n await recordVerifiedPayment(ctx, options, local, verified, event);\n // Application fulfillment must see verified payment details, including its status.\n Object.assign(data, {\n id: verified.id,\n tx_ref: verified.tx_ref,\n amount: verified.amount,\n currency: verified.currency,\n status: verified.status,\n });\n }\n if (\"event\" in event && event.event === \"subscription.cancelled\") {\n const customerEmail = event.data.customer?.email;\n const planId = Number(event.data.plan?.id);\n if (customerEmail && Number.isInteger(planId) && planId > 0) {\n const matches = await store.findSubscriptionsByBillingEmailAndPlanId(\n customerEmail,\n planId,\n );\n if (matches.length === 1) {\n const match = matches[0];\n const now = new Date();\n const scheduledEnd = match.cancelAt ?? match.periodEnd;\n const keepPaidAccess =\n match.status !== \"canceled\" &&\n match.endedAt == null &&\n match.cancelAtPeriodEnd &&\n scheduledEnd != null &&\n new Date(scheduledEnd).getTime() > now.getTime();\n const canceled = await store.updateSubscription(match.id, {\n status: keepPaidAccess ? match.status : \"canceled\",\n cancelAtPeriodEnd: keepPaidAccess,\n cancelAt: keepPaidAccess ? scheduledEnd : null,\n canceledAt: match.canceledAt ?? now,\n endedAt: keepPaidAccess ? null : (match.endedAt ?? now),\n updatedAt: now,\n });\n const subscription = canceled ?? match;\n const callbackData = { event, subscription };\n // Callback failures make the webhook retryable; handlers must therefore be idempotent.\n await options.subscription?.onSubscriptionCancel?.(\n callbackData,\n ctx as GenericEndpointContext,\n );\n const plan = await getPlans(options.subscription).then((plans) =>\n plans.find(\n (candidate) => candidate.name.toLowerCase() === match.plan.toLowerCase(),\n ),\n );\n if (plan) {\n await options.subscription?.onSubscriptionUpdate?.(\n { ...callbackData, subscription, plan },\n ctx as GenericEndpointContext,\n );\n }\n } else if (matches.length > 1) {\n ctx.context.logger.warn(\n \"Flutterwave cancellation event matched multiple local subscriptions; manual reconciliation is required\",\n );\n }\n }\n }\n await options.onEvent?.(event);\n await store.updateWebhookEvent(eventId, {\n status: \"processed\",\n processedAt: new Date(),\n updatedAt: new Date(),\n });\n } catch (error) {\n ctx.context.logger.error(\"Flutterwave webhook processing failed\", error);\n await store.updateWebhookEvent(eventId, { status: \"failed\", updatedAt: new Date() });\n throw new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"Webhook processing failed; retry delivery\",\n });\n }\n return ctx.json({ received: true });\n },\n );\n","import { mergeSchema, type BetterAuthPluginDBSchema, type DBFieldAttribute } from \"better-auth/db\";\n\nimport type { FlutterwaveOptions } from \"./types.ts\";\n\ntype PluginSchemaTable<TableName extends string, FieldName extends string> = Record<\n TableName,\n {\n fields: Record<FieldName, DBFieldAttribute>;\n disableMigration?: boolean;\n modelName?: string;\n }\n>;\n\ntype TransactionsSchema = PluginSchemaTable<\n \"flutterwaveTransaction\",\n | \"txRef\"\n | \"transactionId\"\n | \"flwRef\"\n | \"referenceId\"\n | \"userId\"\n | \"amount\"\n | \"chargedAmount\"\n | \"currency\"\n | \"status\"\n | \"paymentPlanId\"\n | \"plan\"\n | \"product\"\n | \"paymentType\"\n | \"subaccountId\"\n | \"metadata\"\n | \"verifiedAt\"\n | \"reconciledAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype SubscriptionsSchema = PluginSchemaTable<\n \"flutterwaveSubscription\",\n | \"plan\"\n | \"referenceId\"\n | \"userId\"\n | \"billingEmail\"\n | \"subscriptionId\"\n | \"paymentPlanId\"\n | \"txRef\"\n | \"encryptedPaymentToken\"\n | \"status\"\n | \"periodStart\"\n | \"periodEnd\"\n | \"trialStart\"\n | \"trialEnd\"\n | \"cancelAtPeriodEnd\"\n | \"cancelAt\"\n | \"canceledAt\"\n | \"endedAt\"\n | \"billingInterval\"\n | \"groupId\"\n | \"seats\"\n | \"pendingPlan\"\n | \"reconciledAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype ProductsSchema = PluginSchemaTable<\n \"flutterwaveProduct\",\n | \"name\"\n | \"description\"\n | \"price\"\n | \"currency\"\n | \"quantity\"\n | \"unlimited\"\n | \"slug\"\n | \"metadata\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype PlansSchema = PluginSchemaTable<\n \"flutterwavePlan\",\n | \"name\"\n | \"description\"\n | \"amount\"\n | \"currency\"\n | \"interval\"\n | \"group\"\n | \"paymentPlanId\"\n | \"metadata\"\n | \"reconciledAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype WebhookEventsSchema = PluginSchemaTable<\n \"flutterwaveWebhookEvent\",\n | \"eventId\"\n | \"eventType\"\n | \"transactionId\"\n | \"txRef\"\n | \"payload\"\n | \"status\"\n | \"processedAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype RefundsSchema = PluginSchemaTable<\n \"flutterwaveRefund\",\n | \"refundId\"\n | \"transactionId\"\n | \"txRef\"\n | \"referenceId\"\n | \"amount\"\n | \"currency\"\n | \"status\"\n | \"reason\"\n | \"metadata\"\n | \"reconciledAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\nexport type FlutterwavePluginSchema = TransactionsSchema &\n SubscriptionsSchema &\n ProductsSchema &\n PlansSchema &\n WebhookEventsSchema &\n RefundsSchema;\n\nexport const transactions: TransactionsSchema = {\n flutterwaveTransaction: {\n fields: {\n txRef: { type: \"string\", required: true, unique: true },\n transactionId: { type: \"number\", required: false, unique: true },\n flwRef: { type: \"string\", required: false, index: true },\n referenceId: { type: \"string\", required: true, index: true },\n userId: { type: \"string\", required: true, index: true },\n amount: { type: \"number\", required: false },\n chargedAmount: { type: \"number\", required: false },\n currency: { type: \"string\", required: true },\n status: { type: \"string\", required: true, index: true },\n paymentPlanId: { type: \"number\", required: false, index: true },\n plan: { type: \"string\", required: false, index: true },\n product: { type: \"string\", required: false },\n paymentType: { type: \"string\", required: false },\n subaccountId: { type: \"string\", required: false, index: true },\n metadata: { type: \"string\", required: false },\n verifiedAt: { type: \"date\", required: false },\n reconciledAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const subscriptions: SubscriptionsSchema = {\n flutterwaveSubscription: {\n fields: {\n plan: { type: \"string\", required: true, index: true },\n referenceId: { type: \"string\", required: true, index: true },\n userId: { type: \"string\", required: true, index: true },\n billingEmail: { type: \"string\", required: true, index: true },\n subscriptionId: { type: \"number\", required: false, unique: true },\n paymentPlanId: { type: \"number\", required: false, index: true },\n txRef: { type: \"string\", required: false, index: true },\n encryptedPaymentToken: { type: \"string\", required: false },\n status: { type: \"string\", required: true, defaultValue: \"incomplete\", index: true },\n periodStart: { type: \"date\", required: false },\n periodEnd: { type: \"date\", required: false },\n trialStart: { type: \"date\", required: false },\n trialEnd: { type: \"date\", required: false },\n cancelAtPeriodEnd: { type: \"boolean\", required: false, defaultValue: false },\n cancelAt: { type: \"date\", required: false },\n canceledAt: { type: \"date\", required: false },\n endedAt: { type: \"date\", required: false },\n billingInterval: { type: \"string\", required: false },\n groupId: { type: \"string\", required: false, index: true },\n seats: { type: \"number\", required: false },\n pendingPlan: { type: \"string\", required: false },\n reconciledAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const products: ProductsSchema = {\n flutterwaveProduct: {\n fields: {\n name: { type: \"string\", required: true },\n description: { type: \"string\", required: false },\n price: { type: \"number\", required: true },\n currency: { type: \"string\", required: true },\n quantity: { type: \"number\", required: false, defaultValue: 0 },\n unlimited: { type: \"boolean\", required: false, defaultValue: true },\n slug: { type: \"string\", required: true, unique: true },\n metadata: { type: \"string\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const plans: PlansSchema = {\n flutterwavePlan: {\n fields: {\n name: { type: \"string\", required: true },\n description: { type: \"string\", required: false },\n amount: { type: \"number\", required: true },\n currency: { type: \"string\", required: true },\n interval: { type: \"string\", required: true },\n group: { type: \"string\", required: false },\n paymentPlanId: { type: \"number\", required: false, unique: true },\n metadata: { type: \"string\", required: false },\n reconciledAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const webhookEvents: WebhookEventsSchema = {\n flutterwaveWebhookEvent: {\n fields: {\n eventId: { type: \"string\", required: true, unique: true },\n eventType: { type: \"string\", required: true, index: true },\n transactionId: { type: \"number\", required: false, index: true },\n txRef: { type: \"string\", required: false, index: true },\n payload: { type: \"string\", required: true },\n status: { type: \"string\", required: true, defaultValue: \"pending\", index: true },\n processedAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const refunds: RefundsSchema = {\n flutterwaveRefund: {\n fields: {\n refundId: { type: \"number\", required: false, unique: true },\n transactionId: { type: \"number\", required: true, index: true },\n txRef: { type: \"string\", required: true, index: true },\n referenceId: { type: \"string\", required: true, index: true },\n amount: { type: \"number\", required: true },\n currency: { type: \"string\", required: true },\n status: { type: \"string\", required: true, index: true },\n reason: { type: \"string\", required: false },\n metadata: { type: \"string\", required: false },\n reconciledAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const flutterwavePluginSchema: FlutterwavePluginSchema = {\n ...transactions,\n ...subscriptions,\n ...products,\n ...plans,\n ...webhookEvents,\n ...refunds,\n};\n\nexport const getSchema = (options: FlutterwaveOptions): BetterAuthPluginDBSchema => {\n const { flutterwaveSubscription: _subscription, ...withoutSubscriptions } =\n flutterwavePluginSchema;\n const baseSchema =\n options.subscription?.enabled === true ? flutterwavePluginSchema : withoutSubscriptions;\n const optionSchema = options.schema as Parameters<typeof mergeSchema>[1];\n\n if (\n options.schema !== undefined &&\n options.subscription?.enabled !== true &&\n \"flutterwaveSubscription\" in options.schema\n ) {\n const { flutterwaveSubscription: _customSubscription, ...restSchema } = optionSchema ?? {};\n return mergeSchema(baseSchema, restSchema);\n }\n\n return mergeSchema(baseSchema, optionSchema);\n};\n","import { randomBytes } from \"node:crypto\";\n\nexport interface FlutterwaveV4Options {\n clientId: string;\n clientSecret: string;\n apiBaseUrl?: string;\n identityUrl?: string;\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n}\n\nexport interface FlutterwaveV4CustomerInput {\n email: string;\n name?: { first?: string; middle?: string; last?: string };\n phone?: { country_code?: string; number?: string };\n address?: {\n city?: string;\n country?: string;\n line1?: string;\n line2?: string;\n postal_code?: string;\n state?: string;\n };\n meta?: Record<string, unknown>;\n idempotencyKey: string;\n traceId?: string;\n}\n\nexport interface FlutterwaveV4CardPaymentMethodInput {\n customerId?: string;\n encrypted_card_number: string;\n encrypted_expiry_month: string;\n encrypted_expiry_year: string;\n encrypted_cvv: string;\n nonce: string;\n idempotencyKey: string;\n traceId?: string;\n}\n\nexport interface FlutterwaveV4ChargeInput {\n amount: number;\n currency: string;\n reference: string;\n customerId: string;\n paymentMethodId: string;\n recurring?: boolean;\n redirectUrl?: string;\n meta?: Record<string, unknown>;\n idempotencyKey: string;\n traceId?: string;\n}\n\nexport interface FlutterwaveV4RefundInput {\n chargeId: string;\n amount: number;\n reason: FlutterwaveV4RefundReason;\n idempotencyKey: string;\n traceId?: string;\n}\n\nexport type FlutterwaveV4RefundReason =\n | \"duplicate\"\n | \"fraudulent\"\n | \"requested_by_customer\"\n | \"expired_uncaptured_charge\";\n\nexport type FlutterwaveV4ChargeAuthorization =\n | { type: \"pin\"; pin: { nonce: string; encrypted_pin: string } }\n | { type: \"otp\"; otp: { code: string } };\n\nexport interface FlutterwaveV4Resource {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface FlutterwaveV4Adapter {\n createCustomer(input: FlutterwaveV4CustomerInput): Promise<FlutterwaveV4Resource>;\n createCardPaymentMethod(\n input: FlutterwaveV4CardPaymentMethodInput,\n ): Promise<FlutterwaveV4Resource>;\n createCharge(input: FlutterwaveV4ChargeInput): Promise<FlutterwaveV4Resource>;\n retrieveCharge(chargeId: string): Promise<FlutterwaveV4Resource>;\n updateChargeAuthorization(input: {\n chargeId: string;\n authorization: FlutterwaveV4ChargeAuthorization;\n idempotencyKey: string;\n traceId?: string;\n }): Promise<FlutterwaveV4Resource>;\n createRefund(input: FlutterwaveV4RefundInput): Promise<FlutterwaveV4Resource>;\n}\n\nconst DEFAULT_IDENTITY_URL =\n \"https://idp.flutterwave.com/realms/flutterwave/protocol/openid-connect/token\";\nconst DEFAULT_API_URL = \"https://f4bexperience.flutterwave.com\";\n\n/**\n * Create a server-only Flutterwave v4 transport. It accepts encrypted card\n * fields only; raw PAN/CVV handling belongs in a PCI-compliant client flow.\n */\nexport function createFlutterwaveV4Adapter(options: FlutterwaveV4Options): FlutterwaveV4Adapter {\n if (!options.clientId || !options.clientSecret) {\n throw new Error(\"Flutterwave v4 clientId and clientSecret are required\");\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") throw new Error(\"Fetch is not available\");\n const baseUrl = (options.apiBaseUrl ?? DEFAULT_API_URL).replace(/\\/+$/, \"\");\n const identityUrl = options.identityUrl ?? DEFAULT_IDENTITY_URL;\n const now = options.now ?? Date.now;\n let token: string | undefined;\n let refreshAt = 0;\n let tokenRequest: Promise<string> | undefined;\n\n const getToken = async (): Promise<string> => {\n if (token !== undefined && token.length > 0 && now() < refreshAt) return token;\n if (tokenRequest) return tokenRequest;\n tokenRequest = (async () => {\n const response = await fetchImpl(identityUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: options.clientId,\n client_secret: options.clientSecret,\n grant_type: \"client_credentials\",\n }),\n });\n const raw = await parseJson(response, \"authenticate\");\n const accessToken = field(raw, \"access_token\");\n const expiresIn = Number(field(raw, \"expires_in\"));\n if (!response.ok || typeof accessToken !== \"string\" || !Number.isFinite(expiresIn)) {\n throw v4Error(\"authenticate\", response.status, raw);\n }\n token = accessToken;\n // Flutterwave recommends refresh at least 60 seconds before expiry.\n refreshAt = now() + Math.max(0, expiresIn - 60) * 1_000;\n return accessToken;\n })().finally(() => {\n tokenRequest = undefined;\n });\n return tokenRequest;\n };\n\n const request = async (\n operation: string,\n path: string,\n input: {\n method?: \"GET\" | \"POST\" | \"PUT\";\n body?: unknown;\n idempotencyKey?: string;\n traceId?: string;\n } = {},\n allowAuthRetry = true,\n ): Promise<FlutterwaveV4Resource> => {\n const method = input.method ?? \"GET\";\n if (method !== \"GET\") validateIdempotencyKey(input.idempotencyKey);\n if (input.traceId !== undefined) validateTraceId(input.traceId);\n const headers = new Headers({\n accept: \"application/json\",\n authorization: `Bearer ${await getToken()}`,\n \"content-type\": \"application/json\",\n });\n if (input.idempotencyKey !== undefined) headers.set(\"x-idempotency-key\", input.idempotencyKey);\n if (input.traceId !== undefined) headers.set(\"x-trace-id\", input.traceId);\n const response = await fetchImpl(`${baseUrl}${path}`, {\n method,\n headers,\n ...(input.body === undefined ? {} : { body: JSON.stringify(input.body) }),\n });\n const raw = await parseJson(response, operation);\n if (response.status === 401 && allowAuthRetry) {\n token = undefined;\n refreshAt = 0;\n // Retry once with a fresh OAuth token; POST idempotency keys make this safe.\n return request(operation, path, input, false);\n }\n if (!response.ok) throw v4Error(operation, response.status, raw);\n const status = field(raw, \"status\");\n const data = field(raw, \"data\");\n if (status !== \"success\" || !isObject(data) || typeof data.id !== \"string\") {\n throw new Error(`Flutterwave v4 ${operation} returned an invalid response`);\n }\n return data as FlutterwaveV4Resource;\n };\n\n const withTraceId = (value?: string) => value ?? randomBytes(16).toString(\"hex\");\n\n return {\n createCustomer: async (input) => {\n const { idempotencyKey, traceId, ...body } = input;\n if (!input.email.includes(\"@\")) throw new Error(\"A valid customer email is required\");\n return request(\"create customer\", \"/customers\", {\n method: \"POST\",\n body,\n idempotencyKey,\n traceId: withTraceId(traceId),\n });\n },\n createCardPaymentMethod: async (input) => {\n const { idempotencyKey, traceId, customerId, ...card } = input;\n if (Object.values(card).some((value) => typeof value !== \"string\" || value.length === 0)) {\n throw new Error(\"Flutterwave v4 requires encrypted card fields and a nonce\");\n }\n return request(\"create payment method\", \"/payment-methods\", {\n method: \"POST\",\n body: {\n type: \"card\",\n card,\n ...(customerId !== undefined ? { customer_id: customerId } : {}),\n },\n idempotencyKey,\n traceId: withTraceId(traceId),\n });\n },\n createCharge: async (input) => {\n validateReference(input.reference);\n if (!Number.isFinite(input.amount) || input.amount < 0.01) {\n throw new Error(\"Flutterwave v4 charge amount must be at least 0.01\");\n }\n const { idempotencyKey, traceId, customerId, paymentMethodId, redirectUrl, ...charge } =\n input;\n return request(\"create charge\", \"/charges\", {\n method: \"POST\",\n body: {\n ...charge,\n customer_id: customerId,\n payment_method_id: paymentMethodId,\n ...(redirectUrl !== undefined ? { redirect_url: redirectUrl } : {}),\n },\n idempotencyKey,\n traceId: withTraceId(traceId),\n });\n },\n retrieveCharge: async (chargeId) => {\n if (!chargeId) throw new Error(\"Flutterwave v4 charge id is required\");\n return request(\"retrieve charge\", `/charges/${encodeURIComponent(chargeId)}`);\n },\n updateChargeAuthorization: async (input) => {\n if (!input.chargeId) throw new Error(\"Flutterwave v4 charge id is required\");\n return request(\n \"update charge authorization\",\n `/charges/${encodeURIComponent(input.chargeId)}`,\n {\n method: \"PUT\",\n body: { authorization: input.authorization },\n idempotencyKey: input.idempotencyKey,\n traceId: withTraceId(input.traceId),\n },\n );\n },\n createRefund: async (input) => {\n if (!input.chargeId || !isV4RefundReason(input.reason)) {\n throw new Error(\"Flutterwave v4 refund chargeId and reason are required\");\n }\n if (!Number.isFinite(input.amount) || input.amount < 0.01) {\n throw new Error(\"Flutterwave v4 refund amount must be at least 0.01\");\n }\n const { idempotencyKey, traceId, chargeId, ...refund } = input;\n return request(\"create refund\", \"/refunds\", {\n method: \"POST\",\n body: { charge_id: chargeId, ...refund },\n idempotencyKey,\n traceId: withTraceId(traceId),\n });\n },\n };\n}\n\nasync function parseJson(response: Response, operation: string): Promise<unknown> {\n try {\n return await response.json();\n } catch (cause) {\n throw new Error(`Flutterwave v4 ${operation} returned non-JSON HTTP ${response.status}`, {\n cause,\n });\n }\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction field(value: unknown, key: string): unknown {\n return isObject(value) ? value[key] : undefined;\n}\n\nfunction validateIdempotencyKey(value: string | undefined): asserts value is string {\n if (value === undefined || value.length === 0 || !/^[\\x21-\\x7E]{12,255}$/.test(value)) {\n throw new Error(\"Flutterwave v4 idempotency keys must be 12-255 printable ASCII characters\");\n }\n}\n\nfunction validateTraceId(value: string): void {\n if (!/^[\\x21-\\x7E]{12,255}$/.test(value)) {\n throw new Error(\"Flutterwave v4 trace ids must be 12-255 printable ASCII characters\");\n }\n}\n\nfunction validateReference(value: string): void {\n if (!/^[A-Za-z0-9-]{6,42}$/.test(value)) {\n throw new Error(\"Flutterwave v4 references must be 6-42 letters, digits, or hyphens\");\n }\n}\n\nfunction isV4RefundReason(value: unknown): value is FlutterwaveV4RefundReason {\n return (\n value === \"duplicate\" ||\n value === \"fraudulent\" ||\n value === \"requested_by_customer\" ||\n value === \"expired_uncaptured_charge\"\n );\n}\n\nfunction v4Error(operation: string, status: number, raw: unknown): Error {\n const message = field(field(raw, \"error\"), \"message\") ?? field(raw, \"message\");\n const error = new Error(\n typeof message === \"string\"\n ? message\n : `Flutterwave v4 ${operation} failed with HTTP ${status}`,\n );\n Object.assign(error, { status, retryable: status === 408 || status === 429 || status >= 500 });\n return error;\n}\n","import type { GenericEndpointContext } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\n\nimport type { AnyFlutterwaveOptions, Subscription } from \"./types.ts\";\nimport { createBillingStore } from \"./billing-store.ts\";\nimport { getPlanByName } from \"./utils.ts\";\n\nexport const getOrganizationSubscription = async (\n ctx: GenericEndpointContext,\n organizationId: string,\n groupId?: string | null,\n): Promise<Subscription | null> => {\n return createBillingStore(ctx).findCurrentSubscription(organizationId, groupId);\n};\n\nexport const checkSeatLimit = async (\n ctx: GenericEndpointContext,\n organizationId: string,\n seatsToAdd = 1,\n): Promise<boolean> => {\n const store = createBillingStore(ctx);\n const subscriptions = (await store.findSubscriptionsByReference(organizationId)).filter(\n (subscription) => subscription.status === \"active\" || subscription.status === \"trialing\",\n );\n const seatLimit = subscriptions.reduce<number | undefined>(\n (maximum, subscription) =>\n typeof subscription.seats === \"number\"\n ? Math.max(maximum ?? subscription.seats, subscription.seats)\n : maximum,\n undefined,\n );\n const members = await store.listMembers(organizationId);\n\n if (seatLimit === undefined) {\n return true; // No subscription, no specific limit enforcement here (or maybe allow depending on config)\n }\n\n if (members.length + seatsToAdd > seatLimit) {\n throw new APIError(\"FORBIDDEN\", {\n message: `Organization member limit reached. Used: ${members.length}, Max: ${seatLimit}`,\n });\n }\n\n return true;\n};\n\nexport async function getOrganizationEntitlements(\n ctx: GenericEndpointContext,\n organizationId: string,\n options: AnyFlutterwaveOptions,\n): Promise<{ limits: Record<string, number>; features: string[] }> {\n const subscriptions = (\n await createBillingStore(ctx).findSubscriptionsByReference(organizationId)\n ).filter(\n (subscription) => subscription.status === \"active\" || subscription.status === \"trialing\",\n );\n const limits: Record<string, number> = {};\n const features = new Set<string>();\n for (const subscription of subscriptions) {\n const plan = await getPlanByName(options, subscription.plan);\n for (const [name, value] of Object.entries(plan?.limits ?? {})) {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n limits[name] = Math.max(limits[name] ?? value, value);\n }\n }\n for (const feature of plan?.features ?? []) features.add(feature);\n }\n return { limits, features: [...features] };\n}\n\nexport const checkTeamLimit = async (\n ctx: GenericEndpointContext,\n organizationId: string,\n maxTeams: number,\n): Promise<boolean> => {\n const teams = await createBillingStore(ctx).listTeams(organizationId);\n\n if (teams.length >= maxTeams) {\n throw new APIError(\"FORBIDDEN\", {\n message: `Organization team limit reached. Max teams: ${maxTeams}`,\n });\n }\n\n return true;\n};\n","/* oxlint-disable typescript/strict-boolean-expressions, no-restricted-imports */\nimport { createHash } from \"node:crypto\";\nimport type { GenericEndpointContext } from \"better-auth\";\nimport * as z from \"zod\";\nimport { APIError } from \"better-auth/api\";\nimport { createBillingStore, type BillingStoreAdapter } from \"./billing-store.ts\";\nimport { recordVerifiedPayment } from \"./billing-lifecycle.ts\";\nimport { createFlutterwaveAdapter } from \"./flutterwave-sdk.ts\";\nimport type { FlutterwaveTransactionData } from \"./flutterwave-contracts.ts\";\nimport {\n createRenewalMetadata,\n parseFlutterwaveMetadata,\n stringifyFlutterwaveMetadata,\n} from \"./metadata.ts\";\nimport { acquireOperation, checkpointOperation, failOperation } from \"./operation-ledger.ts\";\nimport { decryptPaymentToken } from \"./token-crypto.ts\";\nimport type {\n AnyFlutterwaveOptions,\n ChargeRecurringSubscriptionInput,\n ChargeRecurringSubscriptionResult,\n FlutterwaveSyncResult,\n} from \"./types.ts\";\nimport { calculatePlanAmount } from \"./utils.ts\";\n\nfunction adapter(options: AnyFlutterwaveOptions) {\n return createFlutterwaveAdapter({\n publicKey: options.publicKey,\n secretKey: options.secretKey,\n flutterwaveClient: options.flutterwaveClient,\n fetch: options.fetch,\n apiBaseUrl: options.apiBaseUrl,\n });\n}\n\nexport async function syncFlutterwavePlans(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n): Promise<FlutterwaveSyncResult> {\n const remote = await adapter(options).listPaymentPlans();\n const store = createBillingStore(ctx);\n const now = new Date();\n for (const plan of remote) {\n await store.upsertPlanByPaymentPlanId(plan.id, {\n name: plan.name,\n amount: plan.amount,\n currency: plan.currency,\n interval: plan.interval,\n paymentPlanId: plan.id,\n reconciledAt: now,\n createdAt: now,\n updatedAt: now,\n });\n }\n return { status: \"success\", count: remote.length };\n}\n\nexport async function chargeSubscriptionRenewal(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n input: ChargeRecurringSubscriptionInput,\n): Promise<ChargeRecurringSubscriptionResult> {\n const store = createBillingStore(ctx);\n const subscription = await store.findSubscriptionById(input.subscriptionId);\n if (!subscription) throw new APIError(\"NOT_FOUND\", { message: \"Subscription not found\" });\n if (\n subscription.status === \"canceled\" ||\n subscription.endedAt != null ||\n (subscription.cancelAtPeriodEnd &&\n subscription.cancelAt &&\n new Date(subscription.cancelAt) <= new Date())\n ) {\n throw new APIError(\"BAD_REQUEST\", { message: \"Canceled subscriptions cannot be renewed\" });\n }\n if (subscription.paymentPlanId != null || subscription.subscriptionId != null) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Native subscription renewals are managed by Flutterwave\",\n });\n }\n const plan =\n (await store.findPlanByName(subscription.plan)) ??\n (await (async () => {\n const configured = options.subscription?.plans;\n const plans = typeof configured === \"function\" ? await configured() : (configured ?? []);\n return plans.find((candidate) => candidate.name === subscription.plan) ?? null;\n })());\n const amount = input.amount ?? (plan ? calculatePlanAmount(plan, subscription.seats) : undefined);\n if (\n amount === undefined ||\n !Number.isFinite(amount) ||\n amount <= 0 ||\n !plan?.currency ||\n !subscription.billingEmail\n ) {\n throw new APIError(\"BAD_REQUEST\", { message: \"Subscription billing details are incomplete\" });\n }\n if (\n input.renewalId !== undefined &&\n (input.renewalId.length === 0 || input.renewalId.length > 255)\n ) {\n throw new APIError(\"BAD_REQUEST\", { message: \"renewalId must contain 1-255 characters\" });\n }\n const priorTransaction = subscription.txRef\n ? await store.findTransactionByTxRef(subscription.txRef)\n : null;\n const priorMetadata = parseFlutterwaveMetadata(priorTransaction?.metadata);\n const priorOperationId =\n typeof priorMetadata.renewalOperationId === \"string\"\n ? priorMetadata.renewalOperationId\n : undefined;\n const priorOperation = priorOperationId ? await store.findWebhookEvent(priorOperationId) : null;\n const unfinishedPrior = priorOperation !== null && priorOperation.status !== \"processed\";\n const period =\n subscription.periodEnd == null ? \"initial\" : new Date(subscription.periodEnd).toISOString();\n const intent = input.renewalId ?? period;\n const digest = createHash(\"sha256\")\n .update(JSON.stringify([subscription.id, intent]))\n .digest(\"hex\");\n const operationId =\n input.renewalId === undefined && unfinishedPrior\n ? priorOperationId!\n : `internal:renewal:${digest}`;\n const txRef =\n input.renewalId === undefined && unfinishedPrior && priorTransaction\n ? priorTransaction.txRef\n : `flw_renewal_${digest.slice(0, 40)}`;\n if (unfinishedPrior && operationId !== priorOperationId) {\n throw new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"A previous renewal requires reconciliation before starting another intent\",\n });\n }\n const requestedOperation = await store.findWebhookEvent(operationId);\n // A completed period must not be charged again by an early scheduler invocation.\n if (\n !unfinishedPrior &&\n requestedOperation === null &&\n subscription.periodEnd != null &&\n new Date(subscription.periodEnd) > new Date()\n ) {\n throw new APIError(\"BAD_REQUEST\", { message: \"The subscription is not due for renewal\" });\n }\n let operation = await acquireOperation(store, {\n eventId: operationId,\n eventType: \"internal.subscription.renewal\",\n txRef,\n payload: JSON.stringify({ phase: \"reserved\", txRef, amount, currency: plan.currency, period }),\n });\n const progress = renewalIntentSchema.parse(JSON.parse(operation.payload));\n if (progress.amount !== amount || progress.currency !== plan.currency) {\n if (operation.status !== \"processed\") await failOperation(store, operation);\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The renewal intent amount or currency has changed\",\n });\n }\n const provider = adapter(options);\n try {\n let transaction = await store.findTransactionByTxRef(progress.txRef);\n transaction ??= await store.createTransaction({\n txRef: progress.txRef,\n referenceId: subscription.referenceId,\n userId: subscription.userId,\n amount,\n currency: plan.currency,\n status: \"pending\",\n plan: subscription.plan,\n metadata: stringifyFlutterwaveMetadata({\n ...createRenewalMetadata({\n subscriptionId: subscription.id,\n referenceId: subscription.referenceId,\n }),\n renewalOperationId: operationId,\n }),\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n if (operation.status === \"processed\") {\n // Stable renewalId retries return the same verified payment instead of creating a new charge.\n const verified = await provider.verifyTransaction({ txRef: progress.txRef });\n await recordVerifiedPayment(ctx, options, transaction, verified);\n return renewalResult(verified);\n }\n if (progress.phase === \"reserved\") {\n if (progress.period !== period)\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The reserved renewal period has already changed\",\n });\n if (!subscription.encryptedPaymentToken && !input.redirectUrl) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"redirectUrl is required when the subscription has no reusable payment token\",\n });\n }\n // Persist ownership and dispatch intent before the provider call. An ambiguous outcome is never recharged.\n if (\n !(await store.updateCurrentSubscription(subscription, {\n txRef: progress.txRef,\n status: \"past_due\",\n updatedAt: new Date(),\n }))\n )\n throw new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"Subscription changed while reserving renewal; retry later\",\n });\n const token = subscription.encryptedPaymentToken\n ? await decryptPaymentToken(subscription.encryptedPaymentToken, ctx.context.secret)\n : null;\n progress.phase = \"submitted\";\n operation = await checkpointOperation(store, operation, {\n payload: JSON.stringify(progress),\n });\n if (token === null) {\n const checkout = await provider.initializePayment({\n tx_ref: progress.txRef,\n amount,\n currency: plan.currency,\n redirect_url: input.redirectUrl!,\n customer: { email: subscription.billingEmail },\n meta: parseFlutterwaveMetadata(transaction.metadata),\n });\n progress.checkoutUrl = checkout.link;\n progress.phase = \"checkout\";\n operation = await checkpointOperation(store, operation, {\n payload: JSON.stringify(progress),\n status: \"failed\",\n });\n return {\n status: \"pending\",\n data: { kind: \"checkout\", url: checkout.link, txRef: progress.txRef, redirect: true },\n };\n }\n const charged = await provider.chargeToken({\n token,\n amount,\n currency: plan.currency,\n email: subscription.billingEmail,\n tx_ref: progress.txRef,\n });\n // Persist a provider identifier before verification whenever the provider has returned one.\n transaction =\n (await store.updateTransactionByTxRef(progress.txRef, {\n transactionId: charged.id,\n updatedAt: new Date(),\n })) ?? transaction;\n const verified = await provider.verifyTransaction({ transactionId: charged.id });\n await recordVerifiedPayment(ctx, options, transaction, verified);\n operation = await checkpointOperation(store, operation, {\n status: verified.status === \"pending\" ? \"failed\" : \"processed\",\n processedAt: verified.status === \"pending\" ? undefined : new Date(),\n });\n return renewalResult(verified);\n }\n // A previous dispatch may have succeeded even if its response was lost. Query the same reference only.\n if (progress.checkoutUrl !== undefined && transaction.status === \"pending\") {\n operation = await checkpointOperation(store, operation, { status: \"failed\" });\n return {\n status: \"pending\",\n data: {\n kind: \"checkout\",\n url: progress.checkoutUrl,\n txRef: progress.txRef,\n redirect: true,\n },\n };\n }\n const verified = await provider.verifyTransaction({ txRef: progress.txRef });\n await recordVerifiedPayment(ctx, options, transaction, verified);\n operation = await checkpointOperation(store, operation, {\n status: verified.status === \"pending\" ? \"failed\" : \"processed\",\n processedAt: verified.status === \"pending\" ? undefined : new Date(),\n });\n if (verified.status === \"pending\" && progress.checkoutUrl !== undefined) {\n return {\n status: \"pending\",\n data: {\n kind: \"checkout\",\n url: progress.checkoutUrl,\n txRef: progress.txRef,\n redirect: true,\n },\n };\n }\n return renewalResult(verified);\n } catch (error) {\n if (operation.status !== \"processed\") await failOperation(store, operation);\n throw error;\n }\n}\n\nconst renewalIntentSchema = z.object({\n phase: z.enum([\"reserved\", \"submitted\", \"checkout\"]),\n txRef: z.string().min(1),\n amount: z.number().positive(),\n currency: z.string().min(1),\n period: z.string().min(1),\n checkoutUrl: z.string().optional(),\n});\n\nfunction renewalResult(verified: FlutterwaveTransactionData): ChargeRecurringSubscriptionResult {\n return {\n status:\n verified.status === \"successful\"\n ? \"success\"\n : verified.status === \"pending\"\n ? \"pending\"\n : \"failed\",\n data: {\n id: verified.id,\n txRef: verified.tx_ref,\n flwRef: verified.flw_ref ?? undefined,\n amount: verified.amount,\n chargedAmount: verified.charged_amount,\n currency: verified.currency,\n status: verified.status,\n paymentType: verified.payment_type ?? undefined,\n },\n };\n}\n\n/** Call from an independently authorized scheduled job; no browser endpoint is exposed. */\nexport async function processScheduledFlutterwaveCancellations(\n ctx: { context: { adapter: BillingStoreAdapter } },\n options: AnyFlutterwaveOptions,\n input: { now?: Date; limit?: number } = {},\n) {\n const now = input.now ?? new Date();\n const limit = input.limit ?? 100;\n if (!Number.isFinite(now.getTime()) || !Number.isInteger(limit) || limit < 1 || limit > 1000) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"A valid time and limit from 1 to 1000 are required\",\n });\n }\n const store = createBillingStore(ctx);\n const due = await store.listDueCancellations(now, limit);\n const failed: string[] = [];\n let canceled = 0;\n for (const subscription of due) {\n try {\n if (subscription.paymentPlanId != null && subscription.subscriptionId == null) {\n throw new Error(\"Native subscription has not been identified\");\n }\n if (\n subscription.subscriptionId != null &&\n subscription.status !== \"canceled\" &&\n subscription.canceledAt == null\n ) {\n await adapter(options).cancelSubscription(subscription.subscriptionId);\n }\n if (await store.completeScheduledCancellation(subscription, now)) canceled++;\n } catch {\n // Retain the schedule so the next invocation can retry without losing the cancellation.\n failed.push(subscription.id);\n }\n }\n return { canceled, failed, hasMore: due.length === limit };\n}\n\nexport async function refundFlutterwaveTransaction(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n input: { transactionId: number; amount?: number; reason?: string },\n) {\n const store = createBillingStore(ctx);\n const transaction = await store.findTransactionById(input.transactionId);\n if (!transaction) throw new APIError(\"NOT_FOUND\", { message: \"Transaction not found\" });\n const result = await adapter(options).refundTransaction(\n input.transactionId,\n input.amount,\n input.reason,\n );\n const now = new Date();\n return store.createRefund({\n refundId: result.id,\n transactionId: input.transactionId,\n txRef: transaction.txRef,\n referenceId: transaction.referenceId,\n amount: result.amount_refunded ?? result.amount ?? input.amount ?? transaction.amount,\n currency: transaction.currency,\n status: result.status,\n reason: input.reason,\n createdAt: now,\n updatedAt: now,\n });\n}\n","/* oxlint-disable no-restricted-imports, typescript/strict-boolean-expressions */\nimport type { GenericEndpointContext } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\nimport * as z from \"zod\";\nimport { createBillingStore } from \"./billing-store.ts\";\nimport { paymentMatches, recordVerifiedPayment } from \"./billing-lifecycle.ts\";\nimport { createFlutterwaveAdapter } from \"./flutterwave-sdk.ts\";\nimport type { AnyFlutterwaveOptions, FlutterwaveTransactionResponse } from \"./types.ts\";\n\nexport type FlutterwaveReconciliationSource = \"webhook\" | \"queue\" | \"admin\" | \"server\" | \"browser\";\n\nexport interface ReconcileFlutterwaveTransactionInput {\n txRef?: string;\n transactionId?: number;\n source?: FlutterwaveReconciliationSource;\n throwOnError?: boolean;\n}\n\nexport async function reconcileFlutterwaveTransaction(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n input: ReconcileFlutterwaveTransactionInput,\n) {\n const store = createBillingStore(ctx);\n const local = input.txRef\n ? await store.findTransactionByTxRef(input.txRef)\n : input.transactionId\n ? await store.findTransactionById(input.transactionId)\n : null;\n if (!local) throw new APIError(\"NOT_FOUND\", { message: \"Transaction not found\" });\n const provider = createFlutterwaveAdapter({\n publicKey: options.publicKey,\n secretKey: options.secretKey,\n flutterwaveClient: options.flutterwaveClient,\n fetch: options.fetch,\n apiBaseUrl: options.apiBaseUrl,\n });\n const verified = await provider.verifyTransaction({\n txRef: input.txRef,\n transactionId: input.transactionId,\n });\n const matches = paymentMatches(local, verified);\n if (!matches) {\n if (input.throwOnError === false) {\n return {\n ok: false as const,\n source: input.source ?? \"server\",\n txRef: local.txRef,\n error: { code: \"TRANSACTION_MISMATCH\", message: \"Transaction details do not match\" },\n };\n }\n throw new APIError(\"BAD_REQUEST\", { message: \"Transaction details do not match\" });\n }\n await recordVerifiedPayment(ctx, options, local, verified);\n const data: FlutterwaveTransactionResponse = {\n id: verified.id,\n txRef: verified.tx_ref,\n flwRef: verified.flw_ref ?? undefined,\n amount: verified.amount,\n chargedAmount: verified.charged_amount,\n currency: verified.currency,\n status: verified.status,\n paymentType: verified.payment_type ?? undefined,\n };\n return {\n ok: true as const,\n source: input.source ?? \"server\",\n txRef: local.txRef,\n status: verified.status,\n data,\n };\n}\n\nconst refundEnvelopeSchema = z.object({\n status: z.literal(\"success\"),\n data: z.object({\n id: z.coerce.number().int().positive(),\n status: z.string().min(1),\n amount_refunded: z.coerce.number().nonnegative().optional(),\n }),\n});\n\nexport async function reconcileFlutterwaveRefunds(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n) {\n const store = createBillingStore(ctx);\n const pending = await store.listPendingRefunds();\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const baseUrl = (options.apiBaseUrl ?? \"https://api.flutterwave.com\").replace(/\\/+$/, \"\");\n let updated = 0;\n for (const refund of pending) {\n if (!refund.refundId) continue;\n const response = await fetchImpl(`${baseUrl}/v3/refunds/${refund.refundId}`, {\n headers: { authorization: `Bearer ${options.secretKey}` },\n });\n if (!response.ok) continue;\n const parsed = refundEnvelopeSchema.safeParse(await response.json());\n if (!parsed.success || parsed.data.data.id !== refund.refundId) continue;\n await store.updateRefund(refund.id, {\n status: parsed.data.data.status,\n amount: parsed.data.data.amount_refunded ?? refund.amount,\n reconciledAt: new Date(),\n updatedAt: new Date(),\n });\n updated++;\n }\n return { status: \"success\" as const, count: updated };\n}\n","import { defineErrorCodes, type AuthContext, type BetterAuthPlugin } from \"better-auth\";\nimport {\n cancelSubscription,\n createSubscription,\n flutterwaveWebhook,\n getConfig,\n initializeTransaction,\n listPlans,\n listProducts,\n listSubscriptions,\n listTransactions,\n restoreSubscription,\n upgradeSubscription,\n verifyTransaction,\n FLUTTERWAVE_ERROR_CODES,\n} from \"./routes.ts\";\nimport { getSchema } from \"./schema.ts\";\nimport { PACKAGE_VERSION } from \"./version.ts\";\nimport type { AnyFlutterwaveOptions, FlutterwaveClientLike, FlutterwaveOptions } from \"./types.ts\";\n\nexport {\n createCheckoutMetadata,\n createProrationMetadata,\n createRenewalMetadata,\n getMetadataBoolean,\n getMetadataNumber,\n getMetadataString,\n hasFlutterwaveMetadata,\n parseFlutterwaveMetadata,\n stringifyFlutterwaveMetadata,\n} from \"./metadata.ts\";\nexport type { FlutterwaveMetadata } from \"./metadata.ts\";\nexport type { FlutterwaveTokenChargeInput } from \"./flutterwave-contracts.ts\";\nexport { createFlutterwaveAdapter, FlutterwaveAdapterError } from \"./flutterwave-sdk.ts\";\nexport { createFlutterwaveV4Adapter } from \"./flutterwave-v4.ts\";\nexport type {\n FlutterwaveV4Adapter,\n FlutterwaveV4ChargeAuthorization,\n FlutterwaveV4CardPaymentMethodInput,\n FlutterwaveV4ChargeInput,\n FlutterwaveV4CustomerInput,\n FlutterwaveV4Options,\n FlutterwaveV4RefundInput,\n FlutterwaveV4RefundReason,\n FlutterwaveV4Resource,\n} from \"./flutterwave-v4.ts\";\nexport type {\n FlutterwaveAdapter,\n FlutterwaveAdapterOptions,\n FlutterwaveSdkClient,\n} from \"./flutterwave-sdk.ts\";\nexport { decryptPaymentToken, encryptPaymentToken } from \"./token-crypto.ts\";\nexport { checkSeatLimit, checkTeamLimit, getOrganizationEntitlements } from \"./limits.ts\";\nexport {\n chargeSubscriptionRenewal,\n processScheduledFlutterwaveCancellations,\n refundFlutterwaveTransaction,\n syncFlutterwavePlans,\n} from \"./operations.ts\";\nexport { reconcileFlutterwaveRefunds, reconcileFlutterwaveTransaction } from \"./reconciliation.ts\";\nexport type * from \"./types.ts\";\n\ndeclare module \"better-auth\" {\n interface BetterAuthPluginRegistry<AuthOptions, Options> {\n flutterwave: { creator: typeof flutterwave };\n }\n}\n\nconst INTERNAL_ERROR_CODES = defineErrorCodes(\n Object.fromEntries(\n Object.entries(FLUTTERWAVE_ERROR_CODES).map(([key, value]) => [\n key,\n typeof value === \"string\" ? value : value.message,\n ]),\n ),\n);\n\n// Keep this as a type alias so Better Auth can infer the concrete endpoint keys\n// without adding a string index signature to every auth API.\n// oxlint-disable-next-line typescript/consistent-type-definitions\ntype FlutterwavePluginEndpoints = {\n initializeFlutterwaveTransaction: ReturnType<typeof initializeTransaction>;\n verifyFlutterwaveTransaction: ReturnType<typeof verifyTransaction>;\n listFlutterwaveTransactions: ReturnType<typeof listTransactions>;\n listFlutterwaveSubscriptions: ReturnType<typeof listSubscriptions>;\n createFlutterwaveSubscription: ReturnType<typeof createSubscription>;\n upgradeFlutterwaveSubscription: ReturnType<typeof upgradeSubscription>;\n cancelFlutterwaveSubscription: ReturnType<typeof cancelSubscription>;\n restoreFlutterwaveSubscription: ReturnType<typeof restoreSubscription>;\n listFlutterwaveProducts: ReturnType<typeof listProducts>;\n listFlutterwavePlans: ReturnType<typeof listPlans>;\n getFlutterwaveConfig: ReturnType<typeof getConfig>;\n flutterwaveWebhook: ReturnType<typeof flutterwaveWebhook>;\n};\n\ntype FlutterwavePluginInstance<O extends AnyFlutterwaveOptions> = Omit<\n BetterAuthPlugin,\n \"id\" | \"version\" | \"endpoints\" | \"schema\" | \"options\" | \"$ERROR_CODES\" | \"init\"\n> & {\n id: \"flutterwave\";\n version: typeof PACKAGE_VERSION;\n endpoints: FlutterwavePluginEndpoints;\n schema: ReturnType<typeof getSchema>;\n options: NoInfer<O>;\n $ERROR_CODES: typeof INTERNAL_ERROR_CODES;\n init: (ctx: AuthContext) => { options: Record<string, never> };\n};\n\nexport const flutterwave = <\n TFlutterwaveClient extends FlutterwaveClientLike = FlutterwaveClientLike,\n O extends FlutterwaveOptions<TFlutterwaveClient> = FlutterwaveOptions<TFlutterwaveClient>,\n>(\n options: O,\n): FlutterwavePluginInstance<O> => {\n const routeOptions = options as unknown as AnyFlutterwaveOptions;\n return {\n id: \"flutterwave\",\n version: PACKAGE_VERSION,\n endpoints: {\n initializeFlutterwaveTransaction: initializeTransaction(\n routeOptions,\n \"/flutterwave/transaction/initialize\",\n ),\n verifyFlutterwaveTransaction: verifyTransaction(\n routeOptions,\n \"/flutterwave/transaction/verify\",\n ),\n listFlutterwaveTransactions: listTransactions(routeOptions, \"/flutterwave/transaction/list\"),\n listFlutterwaveSubscriptions: listSubscriptions(\n routeOptions,\n \"/flutterwave/subscription/list\",\n ),\n createFlutterwaveSubscription: createSubscription(\n routeOptions,\n \"/flutterwave/subscription/create\",\n ),\n upgradeFlutterwaveSubscription: upgradeSubscription(\n routeOptions,\n \"/flutterwave/subscription/upgrade\",\n ),\n cancelFlutterwaveSubscription: cancelSubscription(\n routeOptions,\n \"/flutterwave/subscription/cancel\",\n ),\n restoreFlutterwaveSubscription: restoreSubscription(\n routeOptions,\n \"/flutterwave/subscription/restore\",\n ),\n listFlutterwaveProducts: listProducts(routeOptions, \"/flutterwave/product/list\"),\n listFlutterwavePlans: listPlans(routeOptions, \"/flutterwave/plan/list\"),\n getFlutterwaveConfig: getConfig(routeOptions, \"/flutterwave/config\"),\n flutterwaveWebhook: flutterwaveWebhook(routeOptions, \"/flutterwave/webhook\"),\n },\n schema: getSchema(routeOptions),\n init: (ctx) => {\n if (options.organization?.enabled === true && !ctx.hasPlugin(\"organization\")) {\n ctx.logger.error(\n \"Flutterwave organization billing requires the Better Auth organization plugin.\",\n );\n }\n return { options: {} };\n },\n $ERROR_CODES: INTERNAL_ERROR_CODES,\n options,\n };\n};\n"],"mappings":";;;;;;;;AAkHA,SAAS,4BACP,eAC2B;CAC3B,MAAM,6BAAa,IAAI,IAAI;EACzB,CAAC,UAAU,CAAC;EACZ,CAAC,YAAY,CAAC;EACd,CAAC,cAAc,CAAC;EAChB,CAAC,YAAY,CAAC;EACd,CAAC,YAAY,CAAC;CAChB,CAAC;CACD,OAAO,CAAC,GAAG,aAAa,CAAC,CAAC,MAAM,GAAG,MAAM;EACvC,MAAM,oBAAoB,WAAW,IAAI,EAAE,MAAM,KAAK,OAAO,WAAW,IAAI,EAAE,MAAM,KAAK;EACzF,OAAO,qBAAqB,IACxB,mBACA,IAA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AIX,YACiC;CACjC,MAAM,eAAe;CACrB,OAAO;EACL,IAAI;EACJ,SAAS;EACT,WAAW;GACT,kCAAkC,sBAChC,cACA,qCACF;GACA,8BAA8B,kBAC5B,cACA,iCACF;GACA,6BAA6B,iBAAiB,cAAc,+BAA+B;GAC3F,8BAA8B,kBAC5B,cACA,gCACF;GACA,+BAA+B,mBAC7B,cACA,kCACF;GACA,gCAAgC,oBAC9B,cACA,mCACF;GACA,+BAA+B,mBAC7B,cACA,kCACF;GACA,gCAAgC,oBAC9B,cACA,mCACF;GACA,yBAAyB,aAAa,cAAc,2BAA2B;GAC/E,sBAAsB,UAAU,cAAc,wBAAwB;GACtE,sBAAsB,UAAU,cAAc,qBAAqB;GACnE,oBAAoB,mBAAmB,cAAc,sBAAsB;EAC7E;EACA,QAAQ,UAAU,YAAY;EAC9B,OAAO,QAAQ;GACb,IAAI,QAAQ,cAAc,YAAY,QAAQ,CAAC,IAAI,UAAU,cAAc,GACzE,IAAI,OAAO,MACT,gFACF;GAEF,OAAO,EAAE,SAAS,CAAC,EAAE;EACvB;EACA,cAAc;EACd;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["NodeBuffer","NodeBuffer","adapter"],"sources":["../src/billing-store.ts","../src/flutterwave-contracts.ts","../src/flutterwave-sdk.ts","../src/operation-ledger.ts","../src/token-crypto.ts","../src/utils.ts","../src/billing-lifecycle.ts","../src/reference-access.ts","../src/route-modules/webhook.ts","../src/route-modules/shared.ts","../src/routes.ts","../src/schema.ts","../src/flutterwave-v4.ts","../src/limits.ts","../src/operations.ts","../src/reconciliation.ts","../src/index.ts"],"sourcesContent":["/* oxlint-disable typescript/no-unnecessary-type-assertion */\nimport type { GenericEndpointContext } from \"better-auth\";\n\nimport type {\n FlutterwavePlan,\n FlutterwaveProduct,\n FlutterwaveRefund,\n FlutterwaveSubscription,\n FlutterwaveTransaction,\n FlutterwaveWebhookEventRecord,\n Member,\n Organization,\n User,\n} from \"./types.ts\";\n\nexport type BillingStoreAdapter = Pick<\n GenericEndpointContext[\"context\"][\"adapter\"],\n \"create\" | \"findOne\" | \"findMany\" | \"update\" | \"updateMany\"\n>;\ntype WhereValue = string | number | boolean | Date | null;\ntype WhereClause = { field: string; value: WhereValue }[];\n\nexport interface BillingStore {\n findSubscriptionById(id: string): Promise<FlutterwaveSubscription | null>;\n findSubscriptionByProviderId(subscriptionId: number): Promise<FlutterwaveSubscription | null>;\n findSubscriptionsByReference(referenceId: string): Promise<FlutterwaveSubscription[]>;\n findCurrentSubscription(\n referenceId: string,\n groupId?: string | null,\n ): Promise<FlutterwaveSubscription | null>;\n retireCompetingSubscriptions(\n referenceId: string,\n groupId: string | null,\n exceptId: string,\n ): Promise<void>;\n findSubscriptionsByTxRef(txRef: string): Promise<FlutterwaveSubscription[]>;\n findSubscriptionsByBillingEmailAndPlanId(\n email: string,\n paymentPlanId: number,\n ): Promise<FlutterwaveSubscription[]>;\n listDueCancellations(now: Date, limit: number): Promise<FlutterwaveSubscription[]>;\n completeScheduledCancellation(subscription: FlutterwaveSubscription, now: Date): Promise<boolean>;\n createSubscription(\n data: Partial<FlutterwaveSubscription> & Record<string, unknown>,\n ): Promise<FlutterwaveSubscription>;\n updateSubscription(\n id: string,\n update: Partial<FlutterwaveSubscription> & Record<string, unknown>,\n ): Promise<FlutterwaveSubscription | null>;\n updateCurrentSubscription(\n subscription: FlutterwaveSubscription,\n update: Partial<FlutterwaveSubscription> & Record<string, unknown>,\n ): Promise<boolean>;\n updateSubscriptionByProviderId(\n subscriptionId: number,\n update: Partial<FlutterwaveSubscription> & Record<string, unknown>,\n ): Promise<FlutterwaveSubscription | null>;\n createTransaction(\n data: Partial<FlutterwaveTransaction> & Record<string, unknown>,\n ): Promise<FlutterwaveTransaction>;\n findTransactionByTxRef(txRef: string): Promise<FlutterwaveTransaction | null>;\n findTransactionById(transactionId: number): Promise<FlutterwaveTransaction | null>;\n updateTransactionByTxRef(\n txRef: string,\n update: Partial<FlutterwaveTransaction> & Record<string, unknown>,\n ): Promise<FlutterwaveTransaction | null>;\n listTransactions(referenceId: string): Promise<FlutterwaveTransaction[]>;\n listProducts(): Promise<FlutterwaveProduct[]>;\n findProductByName(name: string): Promise<FlutterwaveProduct | null>;\n findProductBySlug(slug: string): Promise<FlutterwaveProduct | null>;\n updateProduct(\n id: string,\n update: Partial<FlutterwaveProduct> & Record<string, unknown>,\n ): Promise<void>;\n upsertProductBySlug(\n slug: string,\n data: Partial<FlutterwaveProduct> & Record<string, unknown>,\n ): Promise<void>;\n listPlans(): Promise<FlutterwavePlan[]>;\n findPlanByName(name: string): Promise<FlutterwavePlan | null>;\n findPlanByPaymentPlanId(paymentPlanId: number): Promise<FlutterwavePlan | null>;\n upsertPlanByPaymentPlanId(\n paymentPlanId: number,\n data: Partial<FlutterwavePlan> & Record<string, unknown>,\n ): Promise<void>;\n createWebhookEvent(\n data: Partial<FlutterwaveWebhookEventRecord> & Record<string, unknown>,\n ): Promise<FlutterwaveWebhookEventRecord>;\n findWebhookEvent(eventId: string): Promise<FlutterwaveWebhookEventRecord | null>;\n updateWebhookEvent(\n eventId: string,\n update: Partial<FlutterwaveWebhookEventRecord> & Record<string, unknown>,\n ): Promise<FlutterwaveWebhookEventRecord | null>;\n claimWebhookEvent(event: FlutterwaveWebhookEventRecord, now: Date): Promise<boolean>;\n updateOwnedWebhookEvent(\n event: FlutterwaveWebhookEventRecord,\n update: Partial<FlutterwaveWebhookEventRecord>,\n ): Promise<boolean>;\n createRefund(\n data: Partial<FlutterwaveRefund> & Record<string, unknown>,\n ): Promise<FlutterwaveRefund>;\n findRefundByProviderId(refundId: number): Promise<FlutterwaveRefund | null>;\n listPendingRefunds(): Promise<FlutterwaveRefund[]>;\n updateRefund(\n id: string,\n update: Partial<FlutterwaveRefund> & Record<string, unknown>,\n ): Promise<FlutterwaveRefund | null>;\n findUser(id: string): Promise<User | null>;\n findOrganization(id: string): Promise<Organization | null>;\n findOrganizationOwner(organizationId: string): Promise<Member | null>;\n listMembers(organizationId: string): Promise<Member[]>;\n listTeams(organizationId: string): Promise<unknown[]>;\n}\n\nfunction sortSubscriptionsForCurrent(\n subscriptions: FlutterwaveSubscription[],\n): FlutterwaveSubscription[] {\n const statusRank = new Map([\n [\"active\", 0],\n [\"trialing\", 1],\n [\"incomplete\", 2],\n [\"past_due\", 3],\n [\"canceled\", 4],\n ]);\n return [...subscriptions].sort((a, b) => {\n const statusDifference = (statusRank.get(a.status) ?? 99) - (statusRank.get(b.status) ?? 99);\n return statusDifference !== 0\n ? statusDifference\n : new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();\n });\n}\n\nexport function createBillingStore(ctx: {\n context: { adapter: BillingStoreAdapter };\n}): BillingStore {\n return createBillingStoreFromAdapter(ctx.context.adapter);\n}\n\nexport function createBillingStoreFromAdapter(adapter: BillingStoreAdapter): BillingStore {\n const findOne = async <T>(model: string, where: WhereClause): Promise<T | null> =>\n (await adapter.findOne<T>({ model, where })) ?? null;\n const findMany = async <T>(model: string, where?: WhereClause): Promise<T[]> =>\n (await adapter.findMany<T>({ model, ...(where ? { where } : {}) })) ?? [];\n\n return {\n findSubscriptionById: (id) => findOne(\"flutterwaveSubscription\", [{ field: \"id\", value: id }]),\n findSubscriptionByProviderId: (subscriptionId) =>\n findOne(\"flutterwaveSubscription\", [{ field: \"subscriptionId\", value: subscriptionId }]),\n findSubscriptionsByReference: (referenceId) =>\n findMany(\"flutterwaveSubscription\", [{ field: \"referenceId\", value: referenceId }]),\n async findCurrentSubscription(referenceId, groupId) {\n const candidates = await this.findSubscriptionsByReference(referenceId);\n const scoped =\n groupId === undefined\n ? candidates\n : candidates.filter(({ groupId: candidateGroup }) =>\n groupId === null\n ? candidateGroup === undefined || candidateGroup === null || candidateGroup === \"\"\n : candidateGroup === groupId,\n );\n return sortSubscriptionsForCurrent(scoped)[0] ?? null;\n },\n async retireCompetingSubscriptions(referenceId, groupId, exceptId) {\n const candidates = await this.findSubscriptionsByReference(referenceId);\n const current = candidates.find(({ id }) => id === exceptId);\n if (!current) return;\n const now = new Date();\n for (const candidate of candidates) {\n const sameGroup =\n groupId === null\n ? candidate.groupId === undefined ||\n candidate.groupId === null ||\n candidate.groupId === \"\"\n : candidate.groupId === groupId;\n if (\n candidate.id !== exceptId &&\n new Date(candidate.createdAt).getTime() <= new Date(current.createdAt).getTime() &&\n sameGroup &&\n [\"active\", \"trialing\", \"incomplete\", \"past_due\"].includes(candidate.status)\n ) {\n await this.updateSubscription(candidate.id, {\n status: \"canceled\",\n cancelAtPeriodEnd: false,\n canceledAt: now,\n endedAt: now,\n updatedAt: now,\n });\n }\n }\n },\n findSubscriptionsByTxRef: (txRef) =>\n findMany(\"flutterwaveSubscription\", [{ field: \"txRef\", value: txRef }]),\n findSubscriptionsByBillingEmailAndPlanId: (email, paymentPlanId) =>\n findMany(\"flutterwaveSubscription\", [\n { field: \"billingEmail\", value: email },\n { field: \"paymentPlanId\", value: paymentPlanId },\n ]),\n listDueCancellations: (now, limit) =>\n adapter.findMany({\n model: \"flutterwaveSubscription\",\n where: [\n { field: \"cancelAtPeriodEnd\", value: true },\n { field: \"cancelAt\", value: now, operator: \"lte\" },\n ],\n sortBy: { field: \"cancelAt\", direction: \"asc\" },\n limit,\n }),\n async completeScheduledCancellation(subscription, now) {\n const count = await adapter.updateMany({\n model: \"flutterwaveSubscription\",\n where: [\n { field: \"id\", value: subscription.id },\n { field: \"cancelAtPeriodEnd\", value: true },\n {\n field: \"cancelAt\",\n value: subscription.cancelAt == null ? null : new Date(subscription.cancelAt),\n },\n ],\n update: {\n status: \"canceled\",\n cancelAtPeriodEnd: false,\n canceledAt: subscription.canceledAt ?? now,\n endedAt: subscription.cancelAt ?? now,\n updatedAt: now,\n },\n });\n return count === 1;\n },\n createSubscription: (data) =>\n adapter.create({\n model: \"flutterwaveSubscription\",\n data,\n }) as Promise<FlutterwaveSubscription>,\n updateSubscription: (id, update) =>\n adapter.update({\n model: \"flutterwaveSubscription\",\n update,\n where: [{ field: \"id\", value: id }],\n }),\n async updateCurrentSubscription(subscription, update) {\n const count = await adapter.updateMany({\n model: \"flutterwaveSubscription\",\n where: [\n { field: \"id\", value: subscription.id },\n { field: \"status\", value: subscription.status },\n { field: \"txRef\", value: subscription.txRef ?? null },\n ],\n update,\n });\n return count === 1;\n },\n updateSubscriptionByProviderId: (subscriptionId, update) =>\n adapter.update({\n model: \"flutterwaveSubscription\",\n update,\n where: [{ field: \"subscriptionId\", value: subscriptionId }],\n }),\n createTransaction: (data) =>\n adapter.create({ model: \"flutterwaveTransaction\", data }) as Promise<FlutterwaveTransaction>,\n findTransactionByTxRef: (txRef) =>\n findOne(\"flutterwaveTransaction\", [{ field: \"txRef\", value: txRef }]),\n findTransactionById: (transactionId) =>\n findOne(\"flutterwaveTransaction\", [{ field: \"transactionId\", value: transactionId }]),\n updateTransactionByTxRef: (txRef, update) =>\n adapter.update({\n model: \"flutterwaveTransaction\",\n update,\n where: [{ field: \"txRef\", value: txRef }],\n }),\n async listTransactions(referenceId) {\n const values = await findMany<FlutterwaveTransaction>(\"flutterwaveTransaction\", [\n { field: \"referenceId\", value: referenceId },\n ]);\n return values.sort(\n (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n );\n },\n async listProducts() {\n const values = await findMany<FlutterwaveProduct>(\"flutterwaveProduct\");\n return values.sort((a, b) => a.name.localeCompare(b.name));\n },\n findProductByName: (name) => findOne(\"flutterwaveProduct\", [{ field: \"name\", value: name }]),\n findProductBySlug: (slug) => findOne(\"flutterwaveProduct\", [{ field: \"slug\", value: slug }]),\n async updateProduct(id, update) {\n await adapter.update({\n model: \"flutterwaveProduct\",\n update,\n where: [{ field: \"id\", value: id }],\n });\n },\n async upsertProductBySlug(slug, data) {\n const existing = await this.findProductBySlug(slug);\n if (existing?.id !== undefined) {\n const { createdAt: _createdAt, ...update } = data;\n await this.updateProduct(existing.id, update);\n } else {\n await adapter.create({ model: \"flutterwaveProduct\", data: { ...data, slug } });\n }\n },\n listPlans: () => findMany(\"flutterwavePlan\"),\n findPlanByName: (name) => findOne(\"flutterwavePlan\", [{ field: \"name\", value: name }]),\n findPlanByPaymentPlanId: (paymentPlanId) =>\n findOne(\"flutterwavePlan\", [{ field: \"paymentPlanId\", value: paymentPlanId }]),\n async upsertPlanByPaymentPlanId(paymentPlanId, data) {\n const existing = await this.findPlanByPaymentPlanId(paymentPlanId);\n if (existing?.id !== undefined) {\n const { createdAt: _createdAt, ...update } = data;\n await adapter.update({\n model: \"flutterwavePlan\",\n update,\n where: [{ field: \"id\", value: existing.id }],\n });\n } else {\n await adapter.create({ model: \"flutterwavePlan\", data: { ...data, paymentPlanId } });\n }\n },\n createWebhookEvent: (data) =>\n adapter.create({\n model: \"flutterwaveWebhookEvent\",\n data,\n }) as Promise<FlutterwaveWebhookEventRecord>,\n findWebhookEvent: (eventId) =>\n findOne(\"flutterwaveWebhookEvent\", [{ field: \"eventId\", value: eventId }]),\n updateWebhookEvent: (eventId, update) =>\n adapter.update({\n model: \"flutterwaveWebhookEvent\",\n update,\n where: [{ field: \"eventId\", value: eventId }],\n }),\n async claimWebhookEvent(event, now) {\n const claimed = await adapter.updateMany({\n model: \"flutterwaveWebhookEvent\",\n where: [\n { field: \"eventId\", value: event.eventId },\n { field: \"status\", value: event.status },\n { field: \"updatedAt\", value: new Date(event.updatedAt) },\n ],\n update: { status: \"processing\", updatedAt: now },\n });\n return claimed === 1;\n },\n async updateOwnedWebhookEvent(event, update) {\n const count = await adapter.updateMany({\n model: \"flutterwaveWebhookEvent\",\n where: [\n { field: \"eventId\", value: event.eventId },\n { field: \"status\", value: \"processing\" },\n { field: \"updatedAt\", value: new Date(event.updatedAt) },\n ],\n update,\n });\n return count === 1;\n },\n createRefund: (data) =>\n adapter.create({ model: \"flutterwaveRefund\", data }) as Promise<FlutterwaveRefund>,\n findRefundByProviderId: (refundId) =>\n findOne(\"flutterwaveRefund\", [{ field: \"refundId\", value: refundId }]),\n listPendingRefunds: () =>\n adapter.findMany({\n model: \"flutterwaveRefund\",\n where: [\n {\n field: \"status\",\n operator: \"in\",\n value: [\"pending\", \"completed\", \"processing\", \"pending-momo\"],\n },\n ],\n }),\n updateRefund: (id, update) =>\n adapter.update({ model: \"flutterwaveRefund\", update, where: [{ field: \"id\", value: id }] }),\n findUser: (id) => findOne(\"user\", [{ field: \"id\", value: id }]),\n findOrganization: (id) => findOne(\"organization\", [{ field: \"id\", value: id }]),\n findOrganizationOwner: (organizationId) =>\n findOne(\"member\", [\n { field: \"organizationId\", value: organizationId },\n { field: \"role\", value: \"owner\" },\n ]),\n listMembers: (organizationId) =>\n findMany(\"member\", [{ field: \"organizationId\", value: organizationId }]),\n listTeams: (organizationId) =>\n findMany(\"team\", [{ field: \"organizationId\", value: organizationId }]),\n };\n}\n","/* oxlint-disable no-restricted-imports */\nimport * as z from \"zod\";\n\nconst currencySchema = z.string().regex(/^[A-Z]{3}$/, \"Currency must be a three-letter ISO code\");\nconst positiveAmountSchema = z.coerce.number().positive();\nconst optionalDateSchema = z.string().nullable().optional();\n\nexport const flutterwaveEnvelopeSchema = <T extends z.ZodType>(data: T) =>\n z\n .object({\n status: z.string(),\n message: z.string().optional(),\n data,\n })\n .passthrough();\n\nexport const standardCheckoutInputSchema = z\n .object({\n tx_ref: z.string().min(1).max(100),\n amount: positiveAmountSchema,\n currency: currencySchema,\n redirect_url: z.url(),\n customer: z\n .object({\n email: z.email(),\n name: z.string().min(1).optional(),\n phonenumber: z.string().min(1).optional(),\n })\n .passthrough(),\n payment_options: z.string().min(1).optional(),\n payment_plan: z.number().int().positive().optional(),\n subaccounts: z\n .array(\n z\n .object({\n id: z.string().min(1),\n transaction_charge_type: z.enum([\"flat\", \"percentage\"]).optional(),\n transaction_charge: z.number().nonnegative().optional(),\n })\n .passthrough(),\n )\n .min(1)\n .optional(),\n customizations: z\n .object({\n title: z.string().optional(),\n description: z.string().optional(),\n logo: z.url().optional(),\n })\n .optional(),\n meta: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough();\n\nexport const checkoutDataSchema = z\n .object({\n link: z.url(),\n })\n .passthrough();\n\nexport const transactionSchema = z\n .object({\n id: z.coerce.number().int().positive(),\n tx_ref: z.string().min(1),\n flw_ref: z.string().nullable().optional(),\n amount: positiveAmountSchema,\n charged_amount: z.coerce.number().nonnegative().optional(),\n currency: currencySchema,\n status: z.string().min(1),\n payment_type: z.string().nullable().optional(),\n created_at: optionalDateSchema,\n customer: z\n .object({\n id: z.coerce.number().int().optional(),\n email: z.email(),\n name: z.string().nullable().optional(),\n })\n .passthrough()\n .optional(),\n card: z\n .object({\n token: z.string().min(1).optional(),\n })\n .passthrough()\n .nullable()\n .optional(),\n })\n .passthrough();\n\nexport const paymentPlanSchema = z\n .object({\n id: z.coerce.number().int().positive(),\n name: z.string().min(1),\n amount: positiveAmountSchema\n .nullable()\n .optional()\n .transform((value) => value ?? undefined),\n interval: z.string().min(1),\n currency: currencySchema,\n status: z.string().optional(),\n duration: z.coerce.number().int().nonnegative().optional(),\n created_at: optionalDateSchema,\n })\n .passthrough();\n\nexport const subscriptionSchema = z\n .object({\n id: z.coerce.number().int().positive(),\n amount: positiveAmountSchema,\n customer: z\n .object({\n email: z.email().optional(),\n customer_email: z.email().optional(),\n })\n .passthrough()\n .optional(),\n plan: z.coerce.number().int().positive().optional(),\n status: z.string().min(1),\n currency: currencySchema.optional(),\n created_at: optionalDateSchema,\n })\n .passthrough();\n\nexport const tokenChargeInputSchema = z\n .object({\n token: z.string().min(1),\n currency: currencySchema,\n country: z.string().length(2).toUpperCase().optional(),\n amount: positiveAmountSchema,\n email: z.email(),\n tx_ref: z.string().min(1).max(100),\n narration: z.string().optional(),\n })\n .passthrough();\n\nexport const refundSchema = z\n .object({\n id: z.coerce.number().int().positive().optional(),\n transaction_id: z.coerce.number().int().positive().optional(),\n amount_refunded: z.coerce.number().nonnegative().optional(),\n amount: z.coerce.number().nonnegative().optional(),\n status: z.string().min(1),\n created_at: optionalDateSchema,\n })\n .passthrough();\n\nexport type StandardCheckoutInput = z.infer<typeof standardCheckoutInputSchema>;\nexport type FlutterwaveCheckoutData = z.infer<typeof checkoutDataSchema>;\nexport type FlutterwaveTransactionData = z.infer<typeof transactionSchema>;\nexport type FlutterwavePaymentPlanData = z.infer<typeof paymentPlanSchema>;\nexport type FlutterwaveSubscriptionData = z.infer<typeof subscriptionSchema>;\nexport type FlutterwaveTokenChargeInput = z.infer<typeof tokenChargeInputSchema>;\nexport type FlutterwaveRefundData = z.infer<typeof refundSchema>;\n","/* oxlint-disable no-restricted-imports */\nimport * as z from \"zod\";\nimport {\n checkoutDataSchema,\n flutterwaveEnvelopeSchema,\n paymentPlanSchema,\n refundSchema,\n standardCheckoutInputSchema,\n subscriptionSchema,\n tokenChargeInputSchema,\n transactionSchema,\n type FlutterwaveCheckoutData,\n type FlutterwavePaymentPlanData,\n type FlutterwaveRefundData,\n type FlutterwaveSubscriptionData,\n type FlutterwaveTokenChargeInput,\n type FlutterwaveTransactionData,\n type StandardCheckoutInput,\n} from \"./flutterwave-contracts.ts\";\n\ntype SdkResult = Promise<unknown>;\n\n/** The deliberately small provider boundary used by this package. */\nexport interface FlutterwaveClient {\n Transaction: {\n verify(input: { id: number }): SdkResult;\n verify_by_tx(input: { tx_ref: string }): SdkResult;\n refund(input: { id: number; amount?: number; comments?: string }): SdkResult;\n };\n PaymentPlan: {\n get_all(input: Record<string, unknown>): SdkResult;\n };\n Subscription: {\n fetch_all(input: Record<string, unknown>): SdkResult;\n cancel(input: { id: number }): SdkResult;\n activate(input: { id: number }): SdkResult;\n };\n Tokenized: {\n charge(input: FlutterwaveTokenChargeInput): SdkResult;\n };\n}\n\n/** @deprecated Use FlutterwaveClient. */\nexport type FlutterwaveSdkClient = FlutterwaveClient;\n\nexport interface FlutterwaveAdapterOptions {\n publicKey: string;\n secretKey: string;\n flutterwaveClient?: FlutterwaveClient;\n fetch?: typeof globalThis.fetch;\n apiBaseUrl?: string;\n}\n\nexport interface VerifyTransactionInput {\n transactionId?: number;\n txRef?: string;\n}\n\nexport interface ListSubscriptionsInput {\n email?: string;\n transactionId?: number;\n plan?: number;\n status?: string;\n page?: number;\n}\n\nexport interface FlutterwaveAdapter {\n initializePayment(input: StandardCheckoutInput): Promise<FlutterwaveCheckoutData>;\n verifyTransaction(input: VerifyTransactionInput): Promise<FlutterwaveTransactionData>;\n listPaymentPlans(): Promise<FlutterwavePaymentPlanData[]>;\n listSubscriptions(input?: ListSubscriptionsInput): Promise<FlutterwaveSubscriptionData[]>;\n cancelSubscription(subscriptionId: number): Promise<FlutterwaveSubscriptionData>;\n activateSubscription(subscriptionId: number): Promise<FlutterwaveSubscriptionData>;\n chargeToken(input: FlutterwaveTokenChargeInput): Promise<FlutterwaveTransactionData>;\n refundTransaction(\n transactionId: number,\n amount?: number,\n reason?: string,\n ): Promise<FlutterwaveRefundData>;\n}\n\nexport class FlutterwaveAdapterError extends Error {\n readonly operation: string;\n readonly status?: number;\n readonly cause?: unknown;\n\n constructor(operation: string, message: string, options?: { status?: number; cause?: unknown }) {\n super(message);\n this.name = \"FlutterwaveAdapterError\";\n this.operation = operation;\n this.status = options?.status;\n this.cause = options?.cause;\n }\n}\n\nfunction queryString(input: Record<string, unknown>): string {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(input)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n query.set(key, String(value));\n }\n }\n const serialized = query.toString();\n return serialized.length === 0 ? \"\" : `?${serialized}`;\n}\n\nfunction createHttpClient(\n fetchImpl: typeof globalThis.fetch,\n apiBaseUrl: string,\n secretKey: string,\n): FlutterwaveClient {\n const request = async (\n path: string,\n method: \"GET\" | \"POST\" | \"PUT\" = \"GET\",\n body?: unknown,\n ): Promise<unknown> => {\n if (typeof fetchImpl !== \"function\") throw new Error(\"Fetch is not available\");\n\n const response = await fetchImpl(`${apiBaseUrl}${path}`, {\n method,\n headers: {\n accept: \"application/json\",\n authorization: `Bearer ${secretKey}`,\n \"content-type\": \"application/json\",\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n\n let raw: unknown;\n try {\n raw = await response.json();\n } catch {\n throw new Error(`Flutterwave returned a non-JSON response (HTTP ${response.status})`);\n }\n\n if (!response.ok) {\n throw new Error(\n messageFromUnknown(raw) ?? `Flutterwave request failed with HTTP ${response.status}`,\n );\n }\n return raw;\n };\n\n const post = (path: string, body: unknown) => request(path, \"POST\", body);\n\n return {\n Transaction: {\n verify: ({ id }) => request(`/v3/transactions/${id}/verify`),\n verify_by_tx: ({ tx_ref }) =>\n request(`/v3/transactions/verify_by_reference${queryString({ tx_ref })}`),\n refund: ({ id, amount, comments }) =>\n post(`/v3/transactions/${id}/refund`, {\n ...(amount === undefined ? {} : { amount }),\n ...(comments === undefined ? {} : { comments }),\n }),\n },\n PaymentPlan: {\n get_all: (query) => request(`/v3/payment-plans${queryString(query)}`),\n },\n Subscription: {\n fetch_all: (query) => request(`/v3/subscriptions${queryString(query)}`),\n cancel: ({ id }) => request(`/v3/subscriptions/${id}/cancel`, \"PUT\"),\n activate: ({ id }) => request(`/v3/subscriptions/${id}/activate`, \"PUT\"),\n },\n Tokenized: {\n charge: (input) => post(\"/v3/tokenized-charges\", input),\n },\n };\n}\n\nfunction messageFromUnknown(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (typeof value !== \"object\" || value === null) return undefined;\n const message = Reflect.get(value, \"message\");\n return typeof message === \"string\" ? message : undefined;\n}\n\nfunction parseEnvelope<T>(operation: string, raw: unknown, dataSchema: z.ZodType<T>): T {\n const envelope = flutterwaveEnvelopeSchema(dataSchema).safeParse(raw);\n if (!envelope.success) {\n throw new FlutterwaveAdapterError(operation, \"Flutterwave returned an invalid response\", {\n cause: envelope.error,\n });\n }\n if (envelope.data.status.toLowerCase() !== \"success\") {\n throw new FlutterwaveAdapterError(\n operation,\n envelope.data.message ?? \"Flutterwave rejected the request\",\n );\n }\n return envelope.data.data;\n}\n\nasync function sdkCall<T>(\n operation: string,\n action: () => Promise<unknown>,\n schema: z.ZodType<T>,\n): Promise<T> {\n try {\n return parseEnvelope(operation, await action(), schema);\n } catch (error) {\n if (error instanceof FlutterwaveAdapterError) throw error;\n throw new FlutterwaveAdapterError(\n operation,\n messageFromUnknown(error) ?? `Flutterwave ${operation} failed`,\n { cause: error },\n );\n }\n}\n\nconst positiveIdSchema = z.number().int().positive();\nconst optionalPositiveAmountSchema = z.number().positive().optional();\n\n/**\n * Creates the provider boundary used by the plugin.\n *\n * Uses Flutterwave's v3 HTTP API directly so applications do not need a separate\n * SDK dependency. Inject `flutterwaveClient` for a custom provider boundary or\n * `fetch` for controlled transport and tests.\n */\nexport function createFlutterwaveAdapter(options: FlutterwaveAdapterOptions): FlutterwaveAdapter {\n if (!options.publicKey)\n throw new FlutterwaveAdapterError(\"configuration\", \"publicKey is required\");\n if (!options.secretKey)\n throw new FlutterwaveAdapterError(\"configuration\", \"secretKey is required\");\n\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const configuredApiBaseUrl = options.apiBaseUrl ?? \"https://api.flutterwave.com\";\n let end = configuredApiBaseUrl.length;\n while (end > 0 && configuredApiBaseUrl.charCodeAt(end - 1) === 47) end--;\n const apiBaseUrl = configuredApiBaseUrl.slice(0, end);\n const client =\n options.flutterwaveClient ?? createHttpClient(fetchImpl, apiBaseUrl, options.secretKey);\n\n return {\n async initializePayment(input) {\n const body = standardCheckoutInputSchema.parse(input);\n if (typeof fetchImpl !== \"function\") {\n throw new FlutterwaveAdapterError(\"initialize payment\", \"Fetch is not available\");\n }\n\n let response: Response;\n try {\n response = await fetchImpl(`${apiBaseUrl}/v3/payments`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${options.secretKey}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n } catch (error) {\n throw new FlutterwaveAdapterError(\n \"initialize payment\",\n messageFromUnknown(error) ?? \"Flutterwave checkout request failed\",\n { cause: error },\n );\n }\n\n let raw: unknown;\n try {\n raw = await response.json();\n } catch (error) {\n throw new FlutterwaveAdapterError(\n \"initialize payment\",\n \"Flutterwave returned a non-JSON response\",\n { status: response.status, cause: error },\n );\n }\n if (!response.ok) {\n throw new FlutterwaveAdapterError(\n \"initialize payment\",\n messageFromUnknown(raw) ?? `Flutterwave checkout failed with HTTP ${response.status}`,\n { status: response.status },\n );\n }\n return parseEnvelope(\"initialize payment\", raw, checkoutDataSchema);\n },\n\n async verifyTransaction(input) {\n if ((input.transactionId === undefined) === (input.txRef === undefined)) {\n throw new FlutterwaveAdapterError(\n \"verify transaction\",\n \"Provide exactly one of transactionId or txRef\",\n );\n }\n return input.transactionId !== undefined\n ? sdkCall(\n \"verify transaction\",\n () => client.Transaction.verify({ id: positiveIdSchema.parse(input.transactionId) }),\n transactionSchema,\n )\n : sdkCall(\n \"verify transaction\",\n () => client.Transaction.verify_by_tx({ tx_ref: z.string().min(1).parse(input.txRef) }),\n transactionSchema,\n );\n },\n\n listPaymentPlans: () =>\n sdkCall(\n \"list payment plans\",\n () => client.PaymentPlan.get_all({}),\n z.array(paymentPlanSchema),\n ),\n\n listSubscriptions: (input = {}) => {\n // Flutterwave's v3 query parameters are serialized as strings while this\n // adapter keeps numeric identifiers in its public interface.\n const query = {\n email: input.email,\n status: input.status,\n ...(input.plan === undefined ? {} : { plan: String(input.plan) }),\n ...(input.transactionId === undefined\n ? {}\n : { transaction_id: String(input.transactionId) }),\n ...(input.page === undefined ? {} : { page: String(input.page) }),\n };\n return sdkCall(\n \"list subscriptions\",\n () => client.Subscription.fetch_all(query),\n z.array(subscriptionSchema),\n );\n },\n\n cancelSubscription: (subscriptionId) =>\n sdkCall(\n \"cancel subscription\",\n () => client.Subscription.cancel({ id: positiveIdSchema.parse(subscriptionId) }),\n subscriptionSchema,\n ),\n\n activateSubscription: (subscriptionId) =>\n sdkCall(\n \"activate subscription\",\n () => client.Subscription.activate({ id: positiveIdSchema.parse(subscriptionId) }),\n subscriptionSchema,\n ),\n\n chargeToken: (input) => {\n const body = tokenChargeInputSchema.parse(input);\n return sdkCall(\"charge token\", () => client.Tokenized.charge(body), transactionSchema);\n },\n\n refundTransaction: (transactionId, amount, reason) =>\n sdkCall(\n \"refund transaction\",\n () =>\n client.Transaction.refund({\n id: positiveIdSchema.parse(transactionId),\n amount: optionalPositiveAmountSchema.parse(amount),\n ...(reason === undefined ? {} : { comments: z.string().min(1).parse(reason) }),\n }),\n refundSchema,\n ),\n };\n}\n\n/** @deprecated Parse SDK responses through a concrete adapter method instead. */\nexport function unwrapSdkResult<T>(result: unknown): T {\n if (typeof result === \"object\" && result !== null && \"data\" in result) {\n return Reflect.get(result, \"data\") as T;\n }\n return result as T;\n}\n\n/** @deprecated The adapter itself is now the operations boundary. */\nexport function getFlutterwaveOps<T>(client: T): T {\n return client;\n}\n","import { APIError } from \"better-auth/api\";\nimport type { BillingStore } from \"./billing-store.ts\";\nimport type { FlutterwaveWebhookEventRecord } from \"./types.ts\";\n\nconst LEASE_MS = 5 * 60_000;\n\nfunction busy(): APIError {\n return new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"Billing operation is in progress; retry later\",\n });\n}\n\n/** Internal operations share the existing unique event ledger; no new database schema is needed. */\nexport async function acquireOperation(\n store: BillingStore,\n input: { eventId: string; eventType: string; txRef: string; payload: string },\n): Promise<FlutterwaveWebhookEventRecord> {\n let existing = await store.findWebhookEvent(input.eventId);\n const now = new Date();\n if (existing === null) {\n try {\n return await store.createWebhookEvent({\n ...input,\n status: \"processing\",\n createdAt: now,\n updatedAt: now,\n });\n } catch (error) {\n existing = await store.findWebhookEvent(input.eventId);\n if (existing === null) throw error;\n }\n }\n if (existing.status === \"processed\") return existing;\n if (\n existing.status === \"processing\" &&\n new Date(existing.updatedAt).getTime() + LEASE_MS > now.getTime()\n )\n throw busy();\n // Distinct lease timestamps also protect callers that race within the same millisecond.\n const claimedAt = new Date(Math.max(now.getTime(), new Date(existing.updatedAt).getTime() + 1));\n if (!(await store.claimWebhookEvent(existing, claimedAt))) throw busy();\n return { ...existing, status: \"processing\", updatedAt: claimedAt };\n}\n\nexport async function checkpointOperation(\n store: BillingStore,\n operation: FlutterwaveWebhookEventRecord,\n update: Partial<FlutterwaveWebhookEventRecord>,\n): Promise<FlutterwaveWebhookEventRecord> {\n const updatedAt = new Date(Math.max(Date.now(), new Date(operation.updatedAt).getTime() + 1));\n if (!(await store.updateOwnedWebhookEvent(operation, { ...update, updatedAt }))) throw busy();\n return { ...operation, ...update, updatedAt };\n}\n\nexport async function failOperation(\n store: BillingStore,\n operation: FlutterwaveWebhookEventRecord,\n): Promise<void> {\n // A stale owner must not overwrite a lease acquired by another worker.\n await store.updateOwnedWebhookEvent(operation, { status: \"failed\", updatedAt: new Date() });\n}\n","const encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nfunction toBase64(value: Uint8Array): string {\n return NodeBuffer.from(value).toString(\"base64url\");\n}\n\nfunction fromBase64(value: string): Uint8Array {\n return new Uint8Array(NodeBuffer.from(value, \"base64url\"));\n}\n\nasync function deriveKey(secret: string): Promise<CryptoKey> {\n const digest = await crypto.subtle.digest(\"SHA-256\", encoder.encode(secret));\n return crypto.subtle.importKey(\"raw\", digest, \"AES-GCM\", false, [\"encrypt\", \"decrypt\"]);\n}\n\nexport async function encryptPaymentToken(token: string, secret: string): Promise<string> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const encrypted = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv },\n await deriveKey(secret),\n encoder.encode(token),\n );\n return `v1.${toBase64(iv)}.${toBase64(new Uint8Array(encrypted))}`;\n}\n\nexport async function decryptPaymentToken(value: string, secret: string): Promise<string> {\n const [version, encodedIv, encodedCiphertext] = value.split(\".\");\n if (version !== \"v1\" || !encodedIv || !encodedCiphertext) {\n throw new Error(\"Unsupported encrypted payment token\");\n }\n const iv = Uint8Array.from(fromBase64(encodedIv));\n const ciphertext = Uint8Array.from(fromBase64(encodedCiphertext));\n const decrypted = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv },\n await deriveKey(secret),\n ciphertext,\n );\n return decoder.decode(decrypted);\n}\nimport { Buffer as NodeBuffer } from \"node:buffer\";\n","import type { GenericEndpointContext } from \"better-auth\";\n\nimport type {\n AnyFlutterwaveOptions,\n FlutterwaveClientLike,\n FlutterwavePlan,\n FlutterwaveProduct,\n Subscription,\n} from \"./types.ts\";\nimport { createBillingStore } from \"./billing-store.ts\";\n\nexport function getPlanSeatAmount(plan: FlutterwavePlan): number | undefined {\n if (plan.seatAmount !== undefined) {\n if (\n typeof plan.seatAmount === \"number\" &&\n Number.isFinite(plan.seatAmount) &&\n plan.seatAmount >= 0\n ) {\n return plan.seatAmount;\n }\n throw new Error(`Invalid seatAmount for plan '${plan.name}'. Expected a finite number.`);\n }\n\n if (plan.seatPriceId === undefined || plan.seatPriceId === null || plan.seatPriceId === \"\") {\n return undefined;\n }\n\n const parsed = typeof plan.seatPriceId === \"string\" ? Number(plan.seatPriceId) : plan.seatPriceId;\n if (typeof parsed === \"number\" && Number.isFinite(parsed) && parsed >= 0) {\n return parsed;\n }\n\n throw new Error(\n `Invalid seatPriceId for plan '${plan.name}'. Expected a numeric amount in the smallest currency unit.`,\n );\n}\n\nexport function calculatePlanAmount(plan: FlutterwavePlan, quantity: number): number {\n return (plan.amount ?? 0) + Math.max(0, quantity - 1) * (getPlanSeatAmount(plan) ?? 0);\n}\n\nexport function normalizeSubscriptionGroup(group: string | undefined | null): string | null {\n const normalized = group?.trim().toLowerCase();\n return normalized === undefined || normalized === \"\" ? null : normalized;\n}\n\nexport function isLocallyManagedSubscription(\n subscription: Pick<Subscription, \"subscriptionId\" | \"paymentPlanId\">,\n): boolean {\n return subscription.subscriptionId === undefined || subscription.subscriptionId === null;\n}\n\nexport function assertLocallyManagedSubscription(\n subscription: Pick<Subscription, \"subscriptionId\" | \"paymentPlanId\">,\n action: string,\n): void {\n if (!isLocallyManagedSubscription(subscription)) {\n throw new Error(\n `Flutterwave-managed subscriptions do not support ${action}. Use local billing for seat-based or prorated subscription changes.`,\n );\n }\n}\n\nexport async function getPlans(\n subscriptionOptions: AnyFlutterwaveOptions[\"subscription\"],\n): Promise<FlutterwavePlan[]> {\n if (subscriptionOptions?.enabled === true) {\n return typeof subscriptionOptions.plans === \"function\"\n ? subscriptionOptions.plans()\n : subscriptionOptions.plans;\n }\n return [];\n}\n\nexport const getPlan: (\n options: AnyFlutterwaveOptions,\n planId: string,\n) => Promise<FlutterwavePlan | null> = async (options, planId) => {\n if (options.subscription?.enabled === true) {\n const plans = await getPlans(options.subscription);\n return plans.find((plan) => plan.name === planId) ?? null;\n }\n return null;\n};\n\nexport async function getPlanByName(\n options: AnyFlutterwaveOptions,\n name: string,\n): Promise<FlutterwavePlan | null> {\n if (typeof name !== \"string\" || name.trim() === \"\") {\n return null;\n }\n if (options.subscription?.enabled === true) {\n const plans = await getPlans(options.subscription);\n const normalizedName = name.toLowerCase();\n return (\n plans.find(\n (plan) => typeof plan.name === \"string\" && plan.name.toLowerCase() === normalizedName,\n ) ?? null\n );\n }\n return null;\n}\n\nexport async function getPlanByPriceId(\n options: AnyFlutterwaveOptions,\n priceId: string,\n): Promise<FlutterwavePlan | null> {\n if (options.subscription?.enabled === true) {\n const plans = await getPlans(options.subscription);\n return plans.find((plan) => plan.name === priceId) ?? null;\n }\n return null;\n}\n\nexport async function getProducts(\n productOptions: AnyFlutterwaveOptions[\"products\"],\n): Promise<FlutterwaveProduct[]> {\n if (productOptions?.products) {\n return typeof productOptions.products === \"function\"\n ? await productOptions.products()\n : productOptions.products;\n }\n return [];\n}\n\nexport async function getProductByName(\n options: AnyFlutterwaveOptions,\n name: string,\n): Promise<FlutterwaveProduct | null> {\n return await getProducts(options.products).then((products) =>\n products !== undefined && products !== null\n ? (products.find((product) => product.name.toLowerCase() === name.toLowerCase()) ?? null)\n : null,\n );\n}\n\nexport function getNextPeriodEnd(startDate: Date, interval: string): Date | null {\n const date = new Date(startDate);\n const day = date.getUTCDate();\n const addMonths = (months: number) => {\n date.setUTCDate(1);\n date.setUTCMonth(date.getUTCMonth() + months);\n const lastDay = new Date(\n Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0),\n ).getUTCDate();\n date.setUTCDate(Math.min(day, lastDay));\n };\n switch (interval) {\n case \"hourly\":\n date.setUTCHours(date.getUTCHours() + 1);\n break;\n case \"daily\":\n date.setUTCDate(date.getUTCDate() + 1);\n break;\n case \"weekly\":\n date.setUTCDate(date.getUTCDate() + 7);\n break;\n case \"monthly\":\n addMonths(1);\n break;\n case \"quarterly\":\n addMonths(3);\n break;\n case \"biannually\":\n case \"bi-annually\":\n addMonths(6);\n break;\n case \"annually\":\n case \"yearly\":\n addMonths(12);\n break;\n default: {\n const recurring = /^every (\\d+) (hours?|days?|weeks?|months?|years?)$/.exec(interval);\n if (!recurring) return null;\n const count = Number(recurring[1]);\n if (!Number.isSafeInteger(count) || count < 1) return null;\n const unit = recurring[2];\n if (unit?.startsWith(\"hour\")) date.setUTCHours(date.getUTCHours() + count);\n else if (unit?.startsWith(\"day\")) date.setUTCDate(date.getUTCDate() + count);\n else if (unit?.startsWith(\"week\")) date.setUTCDate(date.getUTCDate() + count * 7);\n else addMonths(count * (unit?.startsWith(\"year\") ? 12 : 1));\n if (!Number.isFinite(date.getTime())) return null;\n }\n }\n return date;\n}\n\n/**\n * Validates if the amount meets Flutterwave's minimum transaction requirements.\n * Amounts should be in the smallest currency unit (e.g., kobo, cents).\n */\nexport function validateMinAmount(amount: number, currency: string): boolean {\n const minAmounts: Record<string, number> = {\n NGN: 5000, // 50.00\n GHS: 10, // 0.10\n ZAR: 100, // 1.00\n KES: 300, // 3.00\n USD: 200, // 2.00\n XOF: 100, // 1.00\n };\n const min = minAmounts[currency.toUpperCase()];\n return min !== undefined ? amount >= min : true;\n}\n\nexport async function syncProductQuantityFromFlutterwave(\n ctx: GenericEndpointContext,\n productName: string,\n _flutterwaveClient: FlutterwaveClientLike,\n): Promise<void> {\n // Flutterwave does not provide a product catalogue. Inventory is authoritative locally.\n await decrementProductQuantity(ctx, productName);\n}\n\nexport async function decrementProductQuantity(\n ctx: GenericEndpointContext,\n productName: string,\n): Promise<void> {\n const store = createBillingStore(ctx);\n let product = await store.findProductByName(productName);\n\n product ??= await store.findProductBySlug(productName.toLowerCase().replace(/\\s+/g, \"-\"));\n\n if (product !== undefined && product !== null) {\n if (\n product.unlimited !== true &&\n typeof product.quantity === \"number\" &&\n product.quantity > 0 &&\n product.id !== undefined\n ) {\n await store.updateProduct(product.id, {\n quantity: product.quantity - 1,\n updatedAt: new Date(),\n });\n }\n }\n}\n\nexport async function syncSubscriptionSeats(\n ctx: GenericEndpointContext,\n organizationId: string,\n options: AnyFlutterwaveOptions,\n): Promise<void> {\n if (options.subscription?.enabled !== true) return;\n\n const store = createBillingStore(ctx);\n const subscriptions = (await store.findSubscriptionsByReference(organizationId)).filter(\n (subscription) => subscription.status === \"active\" || subscription.status === \"trialing\",\n );\n const seatSubscriptions: Subscription[] = [];\n for (const candidate of subscriptions) {\n const candidatePlan = await getPlanByName(options, candidate.plan);\n if (candidatePlan !== null && getPlanSeatAmount(candidatePlan) !== undefined) {\n seatSubscriptions.push(candidate);\n }\n }\n const members = await store.listMembers(organizationId);\n const quantity = members.length;\n for (const subscription of seatSubscriptions) {\n try {\n assertLocallyManagedSubscription(subscription, \"automatic seat sync\");\n\n // Locally managed subscriptions renew via saved authorizations, so seat count lives in our DB.\n await store.updateSubscription(subscription.id, {\n seats: quantity,\n updatedAt: new Date(),\n });\n } catch (e: unknown) {\n ctx.context.logger.error(\"Failed to sync subscription seats\", e);\n }\n }\n}\n","/* oxlint-disable no-restricted-imports */\nimport type { GenericEndpointContext } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\nimport * as z from \"zod\";\nimport { createBillingStore } from \"./billing-store.ts\";\nimport type { FlutterwaveTransactionData } from \"./flutterwave-contracts.ts\";\nimport { createFlutterwaveAdapter } from \"./flutterwave-sdk.ts\";\nimport { parseFlutterwaveMetadata } from \"./metadata.ts\";\nimport { acquireOperation, checkpointOperation, failOperation } from \"./operation-ledger.ts\";\nimport { encryptPaymentToken } from \"./token-crypto.ts\";\nimport type {\n AnyFlutterwaveOptions,\n FlutterwaveTransaction,\n FlutterwaveWebhookEvent,\n} from \"./types.ts\";\nimport { getNextPeriodEnd, getPlans, normalizeSubscriptionGroup } from \"./utils.ts\";\n\nconst fulfillmentSchema = z.object({\n initialCompletion: z.boolean(),\n completed: z.array(z.enum([\"complete\", \"created\", \"update\"])),\n});\n\nexport function paymentMatches(\n expected: FlutterwaveTransaction,\n verified: FlutterwaveTransactionData,\n): boolean {\n return (\n verified.tx_ref === expected.txRef &&\n verified.amount === expected.amount &&\n verified.currency === expected.currency\n );\n}\n\n/** Shared fulfillment for browser verification, webhooks, and trusted reconciliation. */\nexport async function recordVerifiedPayment(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n expected: FlutterwaveTransaction,\n verified: FlutterwaveTransactionData,\n webhookEvent?: FlutterwaveWebhookEvent,\n): Promise<void> {\n if (!paymentMatches(expected, verified)) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Verified transaction does not match the expected payment\",\n });\n }\n const store = createBillingStore(ctx);\n const now = new Date();\n // A late pending/failed notification must not undo an already verified payment.\n if (expected.status === \"successful\" && verified.status !== \"successful\") return;\n await store.updateTransactionByTxRef(expected.txRef, {\n transactionId: verified.id,\n flwRef: verified.flw_ref,\n chargedAmount: verified.charged_amount,\n paymentType: verified.payment_type,\n status: verified.status,\n verifiedAt: expected.verifiedAt ?? now,\n reconciledAt: now,\n updatedAt: now,\n });\n if (verified.status !== \"successful\" || options.subscription?.enabled !== true) return;\n\n for (const subscription of await store.findSubscriptionsByTxRef(expected.txRef)) {\n if (subscription.status === \"canceled\" || subscription.endedAt != null) continue;\n const group = normalizeSubscriptionGroup(subscription.groupId);\n const siblings = await store.findSubscriptionsByReference(subscription.referenceId);\n const superseded = siblings.some(\n (candidate) =>\n candidate.id !== subscription.id &&\n normalizeSubscriptionGroup(candidate.groupId) === group &&\n (candidate.status === \"active\" ||\n candidate.status === \"trialing\" ||\n (candidate.status === \"canceled\" && candidate.periodStart != null)) &&\n new Date(candidate.createdAt).getTime() > new Date(subscription.createdAt).getTime(),\n );\n if (superseded) {\n await store.updateSubscription(subscription.id, {\n status: \"canceled\",\n canceledAt: now,\n endedAt: now,\n updatedAt: now,\n });\n continue;\n }\n\n let subscriptionId = subscription.subscriptionId;\n if (\n subscription.paymentPlanId != null &&\n subscriptionId == null &&\n subscription.billingEmail != null &&\n subscription.billingEmail !== \"\"\n ) {\n const provider = createFlutterwaveAdapter(options);\n const remote = await provider.listSubscriptions({\n email: subscription.billingEmail,\n plan: subscription.paymentPlanId,\n transactionId: verified.id,\n });\n const candidates = remote.filter((candidate) => candidate.status !== \"cancelled\");\n subscriptionId = candidates.length === 1 ? candidates[0]?.id : undefined;\n }\n const identified = subscription.paymentPlanId == null || subscriptionId != null;\n const paidAt =\n verified.created_at != null && verified.created_at !== \"\"\n ? new Date(verified.created_at)\n : now;\n const paymentTime = Number.isFinite(paidAt.getTime()) ? paidAt : now;\n const renewal = parseFlutterwaveMetadata(expected.metadata).type === \"renewal\";\n const priorEnd = subscription.periodEnd ? new Date(subscription.periodEnd) : null;\n const periodStart =\n renewal && priorEnd !== null && priorEnd > paymentTime ? priorEnd : paymentTime;\n // Renewal operations set past_due before fulfillment. This survives a failure after\n // recording payment, while the conditional status update prevents concurrent retries\n // from advancing a period that another worker has already fulfilled.\n const advancePeriod =\n subscription.periodEnd == null ||\n (renewal ? subscription.status === \"past_due\" : expected.status !== \"successful\");\n const update = {\n subscriptionId,\n status: identified ? \"active\" : \"incomplete\",\n encryptedPaymentToken:\n verified.card?.token !== undefined\n ? await encryptPaymentToken(verified.card.token, ctx.context.secret)\n : subscription.encryptedPaymentToken,\n ...(advancePeriod\n ? {\n periodStart,\n periodEnd: getNextPeriodEnd(periodStart, subscription.billingInterval ?? \"monthly\"),\n }\n : {}),\n reconciledAt: now,\n updatedAt: now,\n };\n if (!identified) {\n await store.updateCurrentSubscription(subscription, update);\n continue;\n }\n let operation = await acquireOperation(store, {\n eventId: `internal:payment:${verified.id}:${subscription.id}`,\n eventType: \"internal.payment.fulfillment\",\n txRef: expected.txRef,\n payload: JSON.stringify({\n initialCompletion: subscription.status === \"incomplete\",\n completed: [],\n }),\n });\n if (operation.status === \"processed\") continue;\n try {\n const progress = fulfillmentSchema.parse(JSON.parse(operation.payload));\n // The ledger retains initial-completion intent even if a prior worker already activated the row.\n const updated = await store.updateCurrentSubscription(subscription, update);\n if (!updated) {\n operation = await checkpointOperation(store, operation, {\n status: \"processed\",\n processedAt: new Date(),\n });\n continue;\n }\n const plan = (await getPlans(options.subscription)).find(\n (candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase(),\n );\n if (plan) {\n const callbackEvent: FlutterwaveWebhookEvent = webhookEvent ?? {\n event: \"charge.completed\",\n data: {\n id: verified.id,\n tx_ref: verified.tx_ref,\n ...(verified.flw_ref !== undefined &&\n verified.flw_ref !== null &&\n verified.flw_ref !== \"\"\n ? { flw_ref: verified.flw_ref }\n : {}),\n status: verified.status,\n amount: verified.amount,\n currency: verified.currency,\n },\n };\n const currentSubscription = { ...subscription, ...update };\n const callbackData = { event: callbackEvent, subscription: currentSubscription, plan };\n const callbacks = [\n {\n key: \"complete\" as const,\n callback: progress.initialCompletion\n ? options.subscription?.onSubscriptionComplete\n : undefined,\n },\n {\n key: \"created\" as const,\n callback: progress.initialCompletion\n ? options.subscription?.onSubscriptionCreated\n : undefined,\n },\n { key: \"update\" as const, callback: options.subscription?.onSubscriptionUpdate },\n ];\n for (const { key, callback } of callbacks) {\n if (progress.completed.includes(key)) continue;\n // Refresh the lease before external work; handlers must still tolerate at-least-once delivery.\n operation = await checkpointOperation(store, operation, {});\n await callback?.(callbackData, ctx);\n progress.completed.push(key);\n operation = await checkpointOperation(store, operation, {\n payload: JSON.stringify(progress),\n });\n }\n }\n await store.retireCompetingSubscriptions(subscription.referenceId, group, subscription.id);\n operation = await checkpointOperation(store, operation, {\n status: \"processed\",\n processedAt: new Date(),\n });\n } catch (error) {\n await failOperation(store, operation);\n throw error;\n }\n }\n}\n","import type { GenericEndpointContext } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\n\nimport type { AnyFlutterwaveOptions, Session, User } from \"./types.ts\";\n\nexport type BillingReferenceAction =\n | \"initialize-transaction\"\n | \"verify-transaction\"\n | \"list-subscriptions\"\n | \"list-transactions\"\n | \"disable-subscription\"\n | \"enable-subscription\"\n | \"get-subscription-manage-link\";\n\nconst DEFAULT_BILLING_ORG_ROLES = [\"owner\", \"admin\"] as const;\n\nfunction normalizeBillingRoles(roles: readonly string[]): Set<string> {\n return new Set(roles.map((value) => value.trim()).filter((value) => value !== \"\"));\n}\n\nexport function getBillingRoles(options: AnyFlutterwaveOptions): readonly string[] {\n return options.organization?.billingRoles ?? DEFAULT_BILLING_ORG_ROLES;\n}\n\nexport function hasBillingRole(\n role: unknown,\n billingRoles: readonly string[] = DEFAULT_BILLING_ORG_ROLES,\n): boolean {\n const allowedRoles = normalizeBillingRoles(billingRoles);\n if (Array.isArray(role)) {\n return role.some((value) => hasBillingRole(value, billingRoles));\n }\n if (typeof role !== \"string\") {\n return false;\n }\n return role\n .split(\",\")\n .map((value) => value.trim())\n .some((value) => allowedRoles.has(value));\n}\n\nexport function resolveBillingReferenceId(input: {\n body?: unknown;\n query?: unknown;\n requestUrl?: string;\n fallbackUserId: string;\n}): string {\n const body = (input.body ?? {}) as Record<string, unknown>;\n const query = (input.query ?? {}) as Record<string, unknown>;\n const requestQueryReferenceId =\n typeof input.requestUrl === \"string\"\n ? (new URL(input.requestUrl).searchParams.get(\"referenceId\") ?? undefined)\n : undefined;\n\n return (\n (body.referenceId as string | undefined) ??\n (query.referenceId as string | undefined) ??\n requestQueryReferenceId ??\n input.fallbackUserId\n );\n}\n\nexport async function authorizeBillingReference(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n data: {\n user: User;\n session: Session;\n referenceId: string;\n action: BillingReferenceAction;\n },\n): Promise<void> {\n if (data.referenceId === data.user.id) return;\n\n if (\n options.subscription?.enabled === true &&\n typeof options.subscription.authorizeReference === \"function\"\n ) {\n const authorized = await options.subscription.authorizeReference(\n {\n user: data.user,\n session: data.session,\n referenceId: data.referenceId,\n action: data.action,\n },\n ctx,\n );\n if (authorized === true) return;\n throw new APIError(\"UNAUTHORIZED\");\n }\n\n if (options.organization?.enabled === true) {\n const member = await ctx.context.adapter.findOne({\n model: \"member\",\n where: [\n { field: \"userId\", value: data.user.id },\n { field: \"organizationId\", value: data.referenceId },\n ],\n });\n\n if (\n member !== null &&\n member !== undefined &&\n hasBillingRole((member as { role?: unknown }).role, getBillingRoles(options))\n ) {\n return;\n }\n }\n\n throw new APIError(\"UNAUTHORIZED\");\n}\n","import type { GenericEndpointContext } from \"better-auth\";\n\nexport function getWebhookRequest(ctx: GenericEndpointContext): Request | undefined {\n return (\n (ctx as unknown as { requestClone?: Request }).requestClone ??\n (ctx as { request?: Request }).request\n );\n}\n\nexport function getWebhookHeaders(ctx: GenericEndpointContext): Headers | undefined {\n return (\n (ctx as GenericEndpointContext & { headers?: Headers }).headers ??\n (ctx.request as unknown as { headers?: Headers })?.headers\n );\n}\n\nexport function getWebhookClientIP(\n ctx: GenericEndpointContext,\n headers: Headers | undefined,\n): string | undefined {\n return (\n headers?.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n headers?.get(\"x-real-ip\") ??\n (ctx.request as unknown as { ip?: string }).ip\n );\n}\n","import { timingSafeEqual } from \"node:crypto\";\nimport { Buffer as NodeBuffer } from \"node:buffer\";\n\nimport type { AnyFlutterwaveOptions, FlutterwaveCheckoutChannel } from \"../types.ts\";\n\nexport const FLUTTERWAVE_ERROR_MESSAGES = {\n SUBSCRIPTION_NOT_FOUND: \"Subscription not found\",\n SUBSCRIPTION_PLAN_NOT_FOUND: \"Subscription plan not found\",\n FAILED_TO_INITIALIZE_TRANSACTION: \"Failed to initialize transaction\",\n FAILED_TO_VERIFY_TRANSACTION: \"Failed to verify transaction\",\n FAILED_TO_DISABLE_SUBSCRIPTION: \"Failed to disable subscription\",\n FAILED_TO_ENABLE_SUBSCRIPTION: \"Failed to enable subscription\",\n EMAIL_VERIFICATION_REQUIRED: \"Email verification is required before you can subscribe to a plan\",\n SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED:\n \"This subscription only supports specific payment channels\",\n} as const;\n\nexport function getAllowedSubscriptionChannels(\n options: AnyFlutterwaveOptions,\n): FlutterwaveCheckoutChannel[] | undefined {\n const channels = options.subscription?.allowedPaymentChannels;\n return Array.isArray(channels) && channels.length > 0 ? channels : undefined;\n}\n\nexport async function hmacSha256Base64(\n secret: string,\n message: string | Uint8Array<ArrayBuffer>,\n): Promise<string> {\n const encoder = new TextEncoder();\n const keyData = encoder.encode(secret);\n const body = typeof message === \"string\" ? encoder.encode(message) : message;\n\n const crypto = globalThis.crypto;\n if (crypto !== undefined && crypto !== null && \"subtle\" in crypto) {\n const subtle = crypto.subtle;\n const key = await subtle.importKey(\"raw\", keyData, { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n ]);\n const signature = await subtle.sign(\"HMAC\", key, body);\n return NodeBuffer.from(signature).toString(\"base64\");\n }\n\n const { createHmac } = await import(\"node:crypto\");\n return createHmac(\"sha256\", secret).update(body).digest(\"base64\");\n}\n\nexport function timingSafeEqualString(left: string, right: string): boolean {\n const leftBytes = NodeBuffer.from(left);\n const rightBytes = NodeBuffer.from(right);\n if (leftBytes.length !== rightBytes.length) return false;\n return timingSafeEqual(leftBytes, rightBytes);\n}\n","/* oxlint-disable no-restricted-imports, typescript/strict-boolean-expressions */\nimport { createHash } from \"node:crypto\";\nimport { HIDE_METADATA } from \"better-auth\";\nimport type { GenericEndpointContext } from \"better-auth\";\nimport {\n APIError,\n getSessionFromCtx,\n originCheckMiddleware,\n sessionMiddleware,\n} from \"better-auth/api\";\nimport { createAuthEndpoint } from \"better-auth/api\";\nimport * as z from \"zod\";\nimport { createBillingStore } from \"./billing-store.ts\";\nimport { paymentMatches, recordVerifiedPayment } from \"./billing-lifecycle.ts\";\nimport type { FlutterwaveTransactionData } from \"./flutterwave-contracts.ts\";\nimport { createFlutterwaveAdapter } from \"./flutterwave-sdk.ts\";\nimport { createCheckoutMetadata, stringifyFlutterwaveMetadata } from \"./metadata.ts\";\nimport { authorizeBillingReference, resolveBillingReferenceId } from \"./reference-access.ts\";\nimport { getWebhookHeaders, getWebhookRequest } from \"./route-modules/webhook.ts\";\nimport {\n FLUTTERWAVE_ERROR_MESSAGES,\n hmacSha256Base64,\n timingSafeEqualString,\n} from \"./route-modules/shared.ts\";\nimport type {\n AnyFlutterwaveOptions,\n FlutterwaveInitializeResult,\n FlutterwaveProduct,\n FlutterwaveTransactionResponse,\n FlutterwaveV4WebhookEvent,\n FlutterwaveWebhookEvent,\n Session,\n User,\n} from \"./types.ts\";\nimport {\n calculatePlanAmount,\n getPlanSeatAmount,\n getPlans,\n normalizeSubscriptionGroup,\n} from \"./utils.ts\";\n\nconst subaccountSchema = z.object({\n id: z.string().min(1),\n transactionSplitRatio: z.number().positive().optional(),\n transactionChargeType: z.enum([\"flat\", \"percentage\", \"flat_subaccount\"]).optional(),\n transactionCharge: z.number().nonnegative().optional(),\n});\n\nconst initializeBodySchema = z.object({\n amount: z.number().positive().optional(),\n currency: z\n .string()\n .length(3)\n .transform((value) => value.toUpperCase())\n .optional(),\n redirectUrl: z.string().url(),\n txRef: z.string().min(1).max(100).optional(),\n referenceId: z.string().optional(),\n plan: z.string().optional(),\n product: z.string().optional(),\n quantity: z.number().int().positive().default(1),\n metadata: z.record(z.string(), z.unknown()).optional(),\n paymentOptions: z.string().optional(),\n subaccounts: z.array(subaccountSchema).optional(),\n});\n\nconst verifyBodySchema = z\n .object({\n transactionId: z.union([z.string(), z.number()]).optional(),\n txRef: z.string().optional(),\n referenceId: z.string().optional(),\n })\n .refine((body) => (body.transactionId === undefined) !== (body.txRef === undefined), {\n message: \"Provide exactly one of transactionId or txRef\",\n });\n\nconst v3WebhookPayloadSchema = z.object({\n event: z.string().min(1),\n data: z\n .object({\n id: z.union([z.string(), z.number()]).optional(),\n tx_ref: z.string().optional(),\n flw_ref: z.string().optional(),\n status: z.string().optional(),\n amount: z.coerce.number().optional(),\n charged_amount: z.coerce.number().optional(),\n currency: z.string().optional(),\n payment_type: z.string().optional(),\n customer: z.object({ email: z.string().optional() }).passthrough().optional(),\n plan: z\n .object({ id: z.union([z.string(), z.number()]).optional() })\n .passthrough()\n .optional(),\n })\n .passthrough(),\n});\n\nconst v4WebhookPayloadSchema = z.object({\n type: z.string().min(1),\n id: z.string().optional(),\n webhook_id: z.string().optional(),\n timestamp: z.union([z.string(), z.number()]).optional(),\n data: z\n .object({\n id: z.string().optional(),\n reference: z.string().optional(),\n status: z.string().optional(),\n amount: z.coerce.number().optional(),\n currency: z.string().optional(),\n customer: z\n .object({ id: z.string().optional(), email: z.string().optional() })\n .passthrough()\n .optional(),\n })\n .passthrough(),\n});\n\nfunction adapter(options: AnyFlutterwaveOptions) {\n return createFlutterwaveAdapter({\n publicKey: options.publicKey,\n secretKey: options.secretKey,\n flutterwaveClient: options.flutterwaveClient,\n fetch: options.fetch,\n apiBaseUrl: options.apiBaseUrl,\n });\n}\n\nfunction mapTransaction(data: FlutterwaveTransactionData): FlutterwaveTransactionResponse {\n return {\n id: data.id,\n txRef: data.tx_ref,\n flwRef: data.flw_ref ?? undefined,\n status: data.status,\n amount: data.amount,\n chargedAmount: data.charged_amount,\n currency: data.currency,\n paymentType: data.payment_type ?? undefined,\n customer: data.customer\n ? {\n email: data.customer.email,\n name: data.customer.name ?? undefined,\n }\n : undefined,\n };\n}\n\nasync function authenticatedReference(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n action:\n | \"initialize-transaction\"\n | \"verify-transaction\"\n | \"list-subscriptions\"\n | \"list-transactions\"\n | \"disable-subscription\"\n | \"enable-subscription\",\n requested?: string,\n): Promise<{ user: User; session: Session; referenceId: string }> {\n const current = await getSessionFromCtx(ctx);\n if (!current) throw new APIError(\"UNAUTHORIZED\");\n const referenceId = requested ?? current.user.id;\n await authorizeBillingReference(ctx, options, {\n user: current.user,\n session: current.session,\n referenceId,\n action,\n });\n return { user: current.user, session: current.session, referenceId };\n}\n\nasync function resolveBillingEmail(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n referenceId: string,\n user: User,\n): Promise<string> {\n if (referenceId === user.id) return user.email;\n if (options.organization?.enabled !== true) throw new APIError(\"UNAUTHORIZED\");\n const store = createBillingStore(ctx);\n const organization = await store.findOrganization(referenceId);\n const explicit = (organization as { email?: string | null } | null)?.email;\n if (explicit) return explicit;\n const owner = await store.findOrganizationOwner(referenceId);\n const ownerUser = owner ? await store.findUser(owner.userId) : null;\n if (!ownerUser?.email) throw new APIError(\"BAD_REQUEST\", { message: \"Billing email not found\" });\n return ownerUser.email;\n}\n\nasync function configuredProducts(options: AnyFlutterwaveOptions): Promise<FlutterwaveProduct[]> {\n const source = options.products?.products;\n if (!source) return [];\n return typeof source === \"function\" ? source() : source;\n}\n\nexport const initializeTransaction = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n {\n method: \"POST\",\n body: initializeBodySchema,\n use: [sessionMiddleware, originCheckMiddleware],\n },\n async (ctx) => {\n const { user, referenceId } = await authenticatedReference(\n ctx,\n options,\n \"initialize-transaction\",\n ctx.body.referenceId,\n );\n if (\n options.subscription?.requireEmailVerification === true &&\n ctx.body.plan &&\n user.emailVerified !== true\n ) {\n throw new APIError(\"BAD_REQUEST\", {\n code: \"EMAIL_VERIFICATION_REQUIRED\",\n message: FLUTTERWAVE_ERROR_MESSAGES.EMAIL_VERIFICATION_REQUIRED,\n });\n }\n\n const billingEmail = await resolveBillingEmail(ctx, options, referenceId, user);\n const plans = await getPlans(options.subscription);\n const plan = ctx.body.plan\n ? plans.find((candidate) => candidate.name.toLowerCase() === ctx.body.plan?.toLowerCase())\n : undefined;\n if (ctx.body.plan && !plan) throw new APIError(\"NOT_FOUND\", { message: \"Plan not found\" });\n\n const products = await configuredProducts(options);\n const product = ctx.body.product\n ? products.find(\n (candidate) =>\n candidate.name.toLowerCase() === ctx.body.product?.toLowerCase() ||\n candidate.slug === ctx.body.product,\n )\n : undefined;\n if (ctx.body.product && !product) {\n throw new APIError(\"NOT_FOUND\", { message: \"Product not found\" });\n }\n if (plan && product) {\n throw new APIError(\"BAD_REQUEST\", { message: \"Select a plan or a product, not both\" });\n }\n if (plan) {\n if (plan.freeTrial?.days !== undefined && plan.freeTrial.days > 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message:\n \"Flutterwave v3 checkout cannot start a no-charge trial. Do not configure freeTrial until a customer-visible tokenization charge and local trial lifecycle are implemented.\",\n });\n }\n if (plan.amount === undefined || !Number.isFinite(plan.amount) || plan.amount <= 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The plan requires a configured positive amount\",\n });\n }\n if (\n ctx.body.quantity > 1 &&\n (plan.paymentPlanId != null || getPlanSeatAmount(plan) === undefined)\n ) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Additional seats require a locally billed per-seat price\",\n });\n }\n }\n\n const amount = plan\n ? calculatePlanAmount(plan, ctx.body.quantity)\n : product\n ? product.price * ctx.body.quantity\n : ctx.body.amount;\n const currency = plan ? plan.currency : product ? product.currency : ctx.body.currency;\n if (!amount || !currency) {\n throw new APIError(\"BAD_REQUEST\", { message: \"amount and currency are required\" });\n }\n\n const requestedSplits = ctx.body.subaccounts ?? options.marketplace?.defaultSplit;\n const allowed = new Set(options.marketplace?.allowedSubaccountIds ?? []);\n if (requestedSplits?.some(({ id }) => !allowed.has(id))) {\n throw new APIError(\"FORBIDDEN\", { message: \"Subaccount is not allowlisted\" });\n }\n const txRef = ctx.body.txRef ?? `flw_${crypto.randomUUID()}`;\n const groupId = normalizeSubscriptionGroup(plan?.group);\n const metadata = createCheckoutMetadata({\n referenceId,\n userId: user.id,\n plan: plan?.name,\n groupId,\n product: product?.name,\n extra: ctx.body.metadata,\n trial: { isTrial: false, requested: false, granted: false },\n });\n const result = await adapter(options).initializePayment({\n tx_ref: txRef,\n amount,\n currency,\n redirect_url: ctx.body.redirectUrl,\n customer: { email: billingEmail, name: user.name },\n payment_options: plan?.paymentPlanId ? \"card\" : ctx.body.paymentOptions,\n payment_plan: plan?.paymentPlanId,\n subaccounts: requestedSplits?.map((split) => ({\n id: split.id,\n transaction_charge_type:\n split.transactionChargeType === \"flat_subaccount\"\n ? \"flat\"\n : split.transactionChargeType,\n transaction_charge: split.transactionCharge,\n transaction_split_ratio: split.transactionSplitRatio,\n })),\n meta: metadata,\n });\n\n const store = createBillingStore(ctx);\n const now = new Date();\n await store.createTransaction({\n txRef,\n referenceId,\n userId: user.id,\n amount,\n currency,\n status: \"pending\",\n plan: plan?.name,\n product: product?.name,\n subaccountId: requestedSplits?.[0]?.id,\n metadata: stringifyFlutterwaveMetadata(metadata),\n createdAt: now,\n updatedAt: now,\n });\n if (plan) {\n await store.createSubscription({\n userId: user.id,\n referenceId,\n plan: plan.name,\n paymentPlanId: plan.paymentPlanId,\n txRef,\n billingEmail,\n status: \"incomplete\",\n seats: ctx.body.quantity,\n groupId,\n cancelAtPeriodEnd: false,\n billingInterval: plan.interval,\n createdAt: now,\n updatedAt: now,\n });\n }\n return {\n kind: \"checkout\",\n url: result.link,\n txRef,\n redirect: true,\n } satisfies FlutterwaveInitializeResult;\n },\n );\n\nexport const verifyTransaction = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n { method: \"POST\", body: verifyBodySchema, use: [sessionMiddleware, originCheckMiddleware] },\n async (ctx) => {\n const store = createBillingStore(ctx);\n const verified = await adapter(options).verifyTransaction({\n transactionId:\n ctx.body.transactionId === undefined ? undefined : Number(ctx.body.transactionId),\n txRef: ctx.body.txRef,\n });\n const expected = await store.findTransactionByTxRef(verified.tx_ref);\n if (!expected) throw new APIError(\"NOT_FOUND\", { message: \"Transaction not found\" });\n if (ctx.body.referenceId !== undefined && ctx.body.referenceId !== expected.referenceId) {\n throw new APIError(\"UNAUTHORIZED\");\n }\n await authenticatedReference(ctx, options, \"verify-transaction\", expected.referenceId);\n if (\n (ctx.body.txRef !== undefined && verified.tx_ref !== ctx.body.txRef) ||\n !paymentMatches(expected, verified) ||\n verified.status !== \"successful\"\n ) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Verified transaction does not match the expected payment\",\n });\n }\n await recordVerifiedPayment(ctx, options, expected, verified);\n return {\n status: verified.status,\n txRef: verified.tx_ref,\n data: mapTransaction(verified),\n };\n },\n );\n\nconst referenceQuerySchema = z.object({ referenceId: z.string().optional() });\n\nexport const listTransactions = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n { method: \"GET\", query: referenceQuerySchema, use: [sessionMiddleware] },\n async (ctx) => {\n const current = await getSessionFromCtx(ctx);\n if (!current) throw new APIError(\"UNAUTHORIZED\");\n const referenceId = resolveBillingReferenceId({\n query: ctx.query,\n requestUrl: ctx.request?.url,\n fallbackUserId: current.user.id,\n });\n await authenticatedReference(ctx, options, \"list-transactions\", referenceId);\n return { transactions: await createBillingStore(ctx).listTransactions(referenceId) };\n },\n );\n\nexport const listSubscriptions = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n { method: \"GET\", query: referenceQuerySchema, use: [sessionMiddleware] },\n async (ctx) => {\n const current = await getSessionFromCtx(ctx);\n if (!current) throw new APIError(\"UNAUTHORIZED\");\n const referenceId = resolveBillingReferenceId({\n query: ctx.query,\n requestUrl: ctx.request?.url,\n fallbackUserId: current.user.id,\n });\n await authenticatedReference(ctx, options, \"list-subscriptions\", referenceId);\n return {\n subscriptions: await createBillingStore(ctx).findSubscriptionsByReference(referenceId),\n };\n },\n );\n\nconst subscriptionBodySchema = z.object({\n subscriptionId: z.union([z.number().int().positive(), z.string().min(1)]),\n atPeriodEnd: z.boolean().optional(),\n});\n\nasync function findSubscription(ctx: GenericEndpointContext, id: string | number) {\n const store = createBillingStore(ctx);\n if (typeof id === \"string\") {\n const local = await store.findSubscriptionById(id);\n if (local) return local;\n }\n const providerId = Number(id);\n return Number.isInteger(providerId) && providerId > 0\n ? store.findSubscriptionByProviderId(providerId)\n : null;\n}\n\nexport const cancelSubscription = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n {\n method: \"POST\",\n body: subscriptionBodySchema,\n use: [sessionMiddleware, originCheckMiddleware],\n },\n async (ctx) => {\n const store = createBillingStore(ctx);\n const local = await findSubscription(ctx, ctx.body.subscriptionId);\n if (!local) throw new APIError(\"NOT_FOUND\", { message: \"Subscription not found\" });\n await authenticatedReference(ctx, options, \"disable-subscription\", local.referenceId);\n const now = new Date();\n if (\n ctx.body.atPeriodEnd === true ||\n options.subscription?.cancelBehavior === \"at_period_end\"\n ) {\n if (!local.periodEnd || !Number.isFinite(new Date(local.periodEnd).getTime())) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The paid subscription period is unknown; cancel immediately instead\",\n });\n }\n if (local.paymentPlanId != null && local.subscriptionId == null) {\n throw new APIError(\"BAD_REQUEST\", {\n message:\n \"The native subscription has not been identified yet; reconcile its payment first\",\n });\n }\n // Stop the next provider charge now; the scheduler ends the already-paid access later.\n if (local.subscriptionId != null && local.cancelAtPeriodEnd !== true) {\n await adapter(options).cancelSubscription(local.subscriptionId);\n }\n await store.updateSubscription(local.id, {\n cancelAtPeriodEnd: true,\n cancelAt: local.periodEnd,\n ...(local.subscriptionId != null ? { canceledAt: local.canceledAt ?? now } : {}),\n updatedAt: now,\n });\n return { status: \"scheduled\" };\n }\n if (local.paymentPlanId != null && local.subscriptionId == null) {\n throw new APIError(\"BAD_REQUEST\", {\n message:\n \"The native subscription has not been identified yet; reconcile its payment first\",\n });\n }\n if (local.subscriptionId != null)\n await adapter(options).cancelSubscription(local.subscriptionId);\n const canceled = await store.updateSubscription(local.id, {\n status: \"canceled\",\n cancelAtPeriodEnd: false,\n canceledAt: now,\n endedAt: now,\n updatedAt: now,\n });\n if (canceled) {\n const plan = await getPlans(options.subscription).then((plans) =>\n plans.find((candidate) => candidate.name.toLowerCase() === local.plan.toLowerCase()),\n );\n if (plan) {\n const callbackData = {\n event: { event: \"subscription.cancelled\", data: {} },\n subscription: canceled,\n };\n await options.subscription?.onSubscriptionCancel?.(\n callbackData,\n ctx as GenericEndpointContext,\n );\n await options.subscription?.onSubscriptionUpdate?.(\n { ...callbackData, plan },\n ctx as GenericEndpointContext,\n );\n }\n }\n return { status: \"canceled\" };\n },\n );\n\nexport const restoreSubscription = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n {\n method: \"POST\",\n body: subscriptionBodySchema.omit({ atPeriodEnd: true }),\n use: [sessionMiddleware, originCheckMiddleware],\n },\n async (ctx) => {\n const store = createBillingStore(ctx);\n const local = await findSubscription(ctx, ctx.body.subscriptionId);\n if (!local) throw new APIError(\"NOT_FOUND\", { message: \"Subscription not found\" });\n await authenticatedReference(ctx, options, \"enable-subscription\", local.referenceId);\n if (\n local.subscriptionId == null &&\n local.periodEnd != null &&\n new Date(local.periodEnd) <= new Date()\n ) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The paid period has ended; renew through checkout instead\",\n });\n }\n if (local.cancelAtPeriodEnd !== true || local.canceledAt != null) {\n if (local.subscriptionId == null) {\n if (local.status === \"active\" && local.endedAt == null) return { status: \"active\" };\n throw new APIError(\"BAD_REQUEST\", {\n message: \"A canceled local subscription requires a new checkout\",\n });\n }\n await adapter(options).activateSubscription(local.subscriptionId);\n }\n await store.updateSubscription(local.id, {\n status: local.cancelAtPeriodEnd === true ? local.status : \"active\",\n cancelAtPeriodEnd: false,\n cancelAt: null,\n canceledAt: null,\n endedAt: null,\n updatedAt: new Date(),\n });\n return { status: local.cancelAtPeriodEnd === true ? local.status : \"active\" };\n },\n );\n\nexport const createSubscription = initializeTransaction;\nexport const upgradeSubscription = initializeTransaction;\nexport const disableFlutterwaveSubscription = cancelSubscription;\nexport const enableFlutterwaveSubscription = restoreSubscription;\n\nexport const listProducts = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(path, { method: \"GET\" }, async (ctx) => {\n const configured = await configuredProducts(options);\n const stored = await createBillingStore(ctx).listProducts();\n return { products: stored.length > 0 ? stored : configured };\n });\n\nexport const listPlans = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(path, { method: \"GET\" }, async (ctx) => {\n const configured = await getPlans(options.subscription);\n const stored = await createBillingStore(ctx).listPlans();\n return { plans: stored.length > 0 ? stored : configured };\n });\n\nexport const getConfig = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(path, { method: \"GET\" }, async (ctx) => ({\n plans: (await createBillingStore(ctx).listPlans()).concat(await getPlans(options.subscription)),\n products: await configuredProducts(options),\n subscriptions: options.subscription?.enabled === true,\n marketplace: options.marketplace !== undefined,\n }));\n\nexport const flutterwaveWebhook = <P extends string>(options: AnyFlutterwaveOptions, path: P) =>\n createAuthEndpoint(\n path,\n {\n method: \"POST\",\n metadata: { ...HIDE_METADATA, openapi: { operationId: \"flutterwaveWebhook\" } },\n cloneRequest: true,\n disableBody: true,\n },\n async (ctx) => {\n const request = getWebhookRequest(ctx as GenericEndpointContext);\n if (!request) throw new APIError(\"BAD_REQUEST\", { message: \"Request is missing\" });\n const rawBytes = new Uint8Array(await request.arrayBuffer());\n const rawBody = new TextDecoder().decode(rawBytes);\n const headers = getWebhookHeaders(ctx as GenericEndpointContext);\n const signature = headers?.get(\"flutterwave-signature\");\n const legacyHash = headers?.get(\"verif-hash\");\n const secretHash = options.webhook?.secretHash ?? options.secretHash;\n if (typeof signature !== \"string\" && typeof legacyHash !== \"string\") {\n throw new APIError(\"UNAUTHORIZED\", { message: \"Missing signature\" });\n }\n const validV4Signature =\n typeof signature === \"string\" &&\n timingSafeEqualString(signature, await hmacSha256Base64(secretHash, rawBytes));\n const validV3Hash =\n typeof legacyHash === \"string\" && timingSafeEqualString(legacyHash, secretHash);\n if (typeof signature === \"string\" ? !validV4Signature : !validV3Hash) {\n throw new APIError(\"UNAUTHORIZED\", { message: \"Invalid signature\" });\n }\n\n let webhookJson: unknown;\n try {\n webhookJson = JSON.parse(rawBody);\n } catch {\n ctx.context.logger.warn(\"Ignoring non-JSON signed Flutterwave webhook\");\n return ctx.json({ received: true });\n }\n const parsedV3 = v3WebhookPayloadSchema.safeParse(webhookJson);\n const parsedV4 = parsedV3.success ? undefined : v4WebhookPayloadSchema.safeParse(webhookJson);\n if (!parsedV3.success && !parsedV4?.success) {\n ctx.context.logger.warn(\"Ignoring malformed signed Flutterwave webhook\");\n return ctx.json({ received: true });\n }\n let event: FlutterwaveWebhookEvent | FlutterwaveV4WebhookEvent;\n if (parsedV3.success) event = parsedV3.data;\n else if (parsedV4?.success) event = parsedV4.data;\n else throw new APIError(\"BAD_REQUEST\", { message: \"Malformed webhook\" });\n\n const providerEventId = \"type\" in event ? (event.webhook_id ?? event.id) : undefined;\n const eventId =\n providerEventId ??\n createHash(\"sha256\")\n .update(\n \"type\" in event\n ? rawBody\n : event.data.id === undefined\n ? rawBody\n : `${event.event}:${String(event.data.id)}:${String(event.data.status ?? \"\")}`,\n )\n .digest(\"hex\");\n const eventType = \"type\" in event ? event.type : event.event;\n const txRef = \"type\" in event ? event.data.reference : event.data.tx_ref;\n const providerTransactionId = \"type\" in event ? undefined : event.data.id;\n const store = createBillingStore(ctx);\n const existingEvent = await store.findWebhookEvent(eventId);\n if (existingEvent?.status === \"processed\") return ctx.json({ received: true });\n const now = new Date();\n const busy = () =>\n new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"Webhook processing is still in progress; retry delivery\",\n });\n if (existingEvent === null) {\n try {\n await store.createWebhookEvent({\n eventId,\n eventType,\n transactionId:\n providerTransactionId !== undefined &&\n Number.isSafeInteger(Number(providerTransactionId))\n ? Number(providerTransactionId)\n : undefined,\n txRef,\n payload: rawBody,\n status: \"processing\",\n createdAt: now,\n updatedAt: now,\n });\n } catch (error) {\n const concurrent = await store.findWebhookEvent(eventId);\n if (concurrent === null) throw error;\n if (concurrent.status === \"processed\") {\n return ctx.json({ received: true });\n }\n throw busy();\n }\n } else {\n const leaseExpiresAt = new Date(existingEvent.updatedAt).getTime() + 5 * 60_000;\n if (existingEvent.status === \"processing\" && leaseExpiresAt > now.getTime()) throw busy();\n if (!(await store.claimWebhookEvent(existingEvent, now))) throw busy();\n }\n\n try {\n const v3TransactionRef = \"event\" in event ? event.data.tx_ref : undefined;\n if (v3TransactionRef && \"event\" in event && event.data.id !== undefined) {\n const data = event.data;\n const local = await store.findTransactionByTxRef(v3TransactionRef);\n if (!local) throw new Error(\"The webhook payment has not been recorded locally yet\");\n const verified = await adapter(options).verifyTransaction({\n transactionId: Number(data.id),\n });\n if (data.status === \"successful\" && verified.status !== \"successful\") {\n throw new Error(\"The provider has not verified the successful payment yet\");\n }\n await recordVerifiedPayment(ctx, options, local, verified, event);\n // Application fulfillment must see verified payment details, including its status.\n Object.assign(data, {\n id: verified.id,\n tx_ref: verified.tx_ref,\n amount: verified.amount,\n currency: verified.currency,\n status: verified.status,\n });\n }\n if (\"event\" in event && event.event === \"subscription.cancelled\") {\n const customerEmail = event.data.customer?.email;\n const planId = Number(event.data.plan?.id);\n if (customerEmail && Number.isInteger(planId) && planId > 0) {\n const matches = await store.findSubscriptionsByBillingEmailAndPlanId(\n customerEmail,\n planId,\n );\n if (matches.length === 1) {\n const match = matches[0];\n const now = new Date();\n const scheduledEnd = match.cancelAt ?? match.periodEnd;\n const keepPaidAccess =\n match.status !== \"canceled\" &&\n match.endedAt == null &&\n match.cancelAtPeriodEnd &&\n scheduledEnd != null &&\n new Date(scheduledEnd).getTime() > now.getTime();\n const canceled = await store.updateSubscription(match.id, {\n status: keepPaidAccess ? match.status : \"canceled\",\n cancelAtPeriodEnd: keepPaidAccess,\n cancelAt: keepPaidAccess ? scheduledEnd : null,\n canceledAt: match.canceledAt ?? now,\n endedAt: keepPaidAccess ? null : (match.endedAt ?? now),\n updatedAt: now,\n });\n const subscription = canceled ?? match;\n const callbackData = { event, subscription };\n // Callback failures make the webhook retryable; handlers must therefore be idempotent.\n await options.subscription?.onSubscriptionCancel?.(\n callbackData,\n ctx as GenericEndpointContext,\n );\n const plan = await getPlans(options.subscription).then((plans) =>\n plans.find(\n (candidate) => candidate.name.toLowerCase() === match.plan.toLowerCase(),\n ),\n );\n if (plan) {\n await options.subscription?.onSubscriptionUpdate?.(\n { ...callbackData, subscription, plan },\n ctx as GenericEndpointContext,\n );\n }\n } else if (matches.length > 1) {\n ctx.context.logger.warn(\n \"Flutterwave cancellation event matched multiple local subscriptions; manual reconciliation is required\",\n );\n }\n }\n }\n await options.onEvent?.(event);\n await store.updateWebhookEvent(eventId, {\n status: \"processed\",\n processedAt: new Date(),\n updatedAt: new Date(),\n });\n } catch (error) {\n ctx.context.logger.error(\"Flutterwave webhook processing failed\", error);\n await store.updateWebhookEvent(eventId, { status: \"failed\", updatedAt: new Date() });\n throw new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"Webhook processing failed; retry delivery\",\n });\n }\n return ctx.json({ received: true });\n },\n );\n","import { mergeSchema, type BetterAuthPluginDBSchema, type DBFieldAttribute } from \"better-auth/db\";\n\nimport type { FlutterwaveOptions } from \"./types.ts\";\n\ntype PluginSchemaTable<TableName extends string, FieldName extends string> = Record<\n TableName,\n {\n fields: Record<FieldName, DBFieldAttribute>;\n disableMigration?: boolean;\n modelName?: string;\n }\n>;\n\ntype TransactionsSchema = PluginSchemaTable<\n \"flutterwaveTransaction\",\n | \"txRef\"\n | \"transactionId\"\n | \"flwRef\"\n | \"referenceId\"\n | \"userId\"\n | \"amount\"\n | \"chargedAmount\"\n | \"currency\"\n | \"status\"\n | \"paymentPlanId\"\n | \"plan\"\n | \"product\"\n | \"paymentType\"\n | \"subaccountId\"\n | \"metadata\"\n | \"verifiedAt\"\n | \"reconciledAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype SubscriptionsSchema = PluginSchemaTable<\n \"flutterwaveSubscription\",\n | \"plan\"\n | \"referenceId\"\n | \"userId\"\n | \"billingEmail\"\n | \"subscriptionId\"\n | \"paymentPlanId\"\n | \"txRef\"\n | \"encryptedPaymentToken\"\n | \"status\"\n | \"periodStart\"\n | \"periodEnd\"\n | \"trialStart\"\n | \"trialEnd\"\n | \"cancelAtPeriodEnd\"\n | \"cancelAt\"\n | \"canceledAt\"\n | \"endedAt\"\n | \"billingInterval\"\n | \"groupId\"\n | \"seats\"\n | \"pendingPlan\"\n | \"reconciledAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype ProductsSchema = PluginSchemaTable<\n \"flutterwaveProduct\",\n | \"name\"\n | \"description\"\n | \"price\"\n | \"currency\"\n | \"quantity\"\n | \"unlimited\"\n | \"slug\"\n | \"metadata\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype PlansSchema = PluginSchemaTable<\n \"flutterwavePlan\",\n | \"name\"\n | \"description\"\n | \"amount\"\n | \"currency\"\n | \"interval\"\n | \"group\"\n | \"paymentPlanId\"\n | \"metadata\"\n | \"reconciledAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype WebhookEventsSchema = PluginSchemaTable<\n \"flutterwaveWebhookEvent\",\n | \"eventId\"\n | \"eventType\"\n | \"transactionId\"\n | \"txRef\"\n | \"payload\"\n | \"status\"\n | \"processedAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\ntype RefundsSchema = PluginSchemaTable<\n \"flutterwaveRefund\",\n | \"refundId\"\n | \"transactionId\"\n | \"txRef\"\n | \"referenceId\"\n | \"amount\"\n | \"currency\"\n | \"status\"\n | \"reason\"\n | \"metadata\"\n | \"reconciledAt\"\n | \"createdAt\"\n | \"updatedAt\"\n>;\n\nexport type FlutterwavePluginSchema = TransactionsSchema &\n SubscriptionsSchema &\n ProductsSchema &\n PlansSchema &\n WebhookEventsSchema &\n RefundsSchema;\n\nexport const transactions: TransactionsSchema = {\n flutterwaveTransaction: {\n fields: {\n txRef: { type: \"string\", required: true, unique: true },\n transactionId: { type: \"number\", required: false, unique: true },\n flwRef: { type: \"string\", required: false, index: true },\n referenceId: { type: \"string\", required: true, index: true },\n userId: { type: \"string\", required: true, index: true },\n amount: { type: \"number\", required: false },\n chargedAmount: { type: \"number\", required: false },\n currency: { type: \"string\", required: true },\n status: { type: \"string\", required: true, index: true },\n paymentPlanId: { type: \"number\", required: false, index: true },\n plan: { type: \"string\", required: false, index: true },\n product: { type: \"string\", required: false },\n paymentType: { type: \"string\", required: false },\n subaccountId: { type: \"string\", required: false, index: true },\n metadata: { type: \"string\", required: false },\n verifiedAt: { type: \"date\", required: false },\n reconciledAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const subscriptions: SubscriptionsSchema = {\n flutterwaveSubscription: {\n fields: {\n plan: { type: \"string\", required: true, index: true },\n referenceId: { type: \"string\", required: true, index: true },\n userId: { type: \"string\", required: true, index: true },\n billingEmail: { type: \"string\", required: true, index: true },\n subscriptionId: { type: \"number\", required: false, unique: true },\n paymentPlanId: { type: \"number\", required: false, index: true },\n txRef: { type: \"string\", required: false, index: true },\n encryptedPaymentToken: { type: \"string\", required: false },\n status: { type: \"string\", required: true, defaultValue: \"incomplete\", index: true },\n periodStart: { type: \"date\", required: false },\n periodEnd: { type: \"date\", required: false },\n trialStart: { type: \"date\", required: false },\n trialEnd: { type: \"date\", required: false },\n cancelAtPeriodEnd: { type: \"boolean\", required: false, defaultValue: false },\n cancelAt: { type: \"date\", required: false },\n canceledAt: { type: \"date\", required: false },\n endedAt: { type: \"date\", required: false },\n billingInterval: { type: \"string\", required: false },\n groupId: { type: \"string\", required: false, index: true },\n seats: { type: \"number\", required: false },\n pendingPlan: { type: \"string\", required: false },\n reconciledAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const products: ProductsSchema = {\n flutterwaveProduct: {\n fields: {\n name: { type: \"string\", required: true },\n description: { type: \"string\", required: false },\n price: { type: \"number\", required: true },\n currency: { type: \"string\", required: true },\n quantity: { type: \"number\", required: false, defaultValue: 0 },\n unlimited: { type: \"boolean\", required: false, defaultValue: true },\n slug: { type: \"string\", required: true, unique: true },\n metadata: { type: \"string\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const plans: PlansSchema = {\n flutterwavePlan: {\n fields: {\n name: { type: \"string\", required: true },\n description: { type: \"string\", required: false },\n amount: { type: \"number\", required: true },\n currency: { type: \"string\", required: true },\n interval: { type: \"string\", required: true },\n group: { type: \"string\", required: false },\n paymentPlanId: { type: \"number\", required: false, unique: true },\n metadata: { type: \"string\", required: false },\n reconciledAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const webhookEvents: WebhookEventsSchema = {\n flutterwaveWebhookEvent: {\n fields: {\n eventId: { type: \"string\", required: true, unique: true },\n eventType: { type: \"string\", required: true, index: true },\n transactionId: { type: \"number\", required: false, index: true },\n txRef: { type: \"string\", required: false, index: true },\n payload: { type: \"string\", required: true },\n status: { type: \"string\", required: true, defaultValue: \"pending\", index: true },\n processedAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const refunds: RefundsSchema = {\n flutterwaveRefund: {\n fields: {\n refundId: { type: \"number\", required: false, unique: true },\n transactionId: { type: \"number\", required: true, index: true },\n txRef: { type: \"string\", required: true, index: true },\n referenceId: { type: \"string\", required: true, index: true },\n amount: { type: \"number\", required: true },\n currency: { type: \"string\", required: true },\n status: { type: \"string\", required: true, index: true },\n reason: { type: \"string\", required: false },\n metadata: { type: \"string\", required: false },\n reconciledAt: { type: \"date\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n};\n\nexport const flutterwavePluginSchema: FlutterwavePluginSchema = {\n ...transactions,\n ...subscriptions,\n ...products,\n ...plans,\n ...webhookEvents,\n ...refunds,\n};\n\nexport const getSchema = (options: FlutterwaveOptions): BetterAuthPluginDBSchema => {\n const { flutterwaveSubscription: _subscription, ...withoutSubscriptions } =\n flutterwavePluginSchema;\n const baseSchema =\n options.subscription?.enabled === true ? flutterwavePluginSchema : withoutSubscriptions;\n const optionSchema = options.schema as Parameters<typeof mergeSchema>[1];\n\n if (\n options.schema !== undefined &&\n options.subscription?.enabled !== true &&\n \"flutterwaveSubscription\" in options.schema\n ) {\n const { flutterwaveSubscription: _customSubscription, ...restSchema } = optionSchema ?? {};\n return mergeSchema(baseSchema, restSchema);\n }\n\n return mergeSchema(baseSchema, optionSchema);\n};\n","import { randomBytes } from \"node:crypto\";\n\nexport interface FlutterwaveV4Options {\n clientId: string;\n clientSecret: string;\n apiBaseUrl?: string;\n identityUrl?: string;\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n}\n\nexport interface FlutterwaveV4CustomerInput {\n email: string;\n name?: { first?: string; middle?: string; last?: string };\n phone?: { country_code?: string; number?: string };\n address?: {\n city?: string;\n country?: string;\n line1?: string;\n line2?: string;\n postal_code?: string;\n state?: string;\n };\n meta?: Record<string, unknown>;\n idempotencyKey: string;\n traceId?: string;\n}\n\nexport interface FlutterwaveV4CardPaymentMethodInput {\n customerId?: string;\n encrypted_card_number: string;\n encrypted_expiry_month: string;\n encrypted_expiry_year: string;\n encrypted_cvv: string;\n nonce: string;\n idempotencyKey: string;\n traceId?: string;\n}\n\nexport interface FlutterwaveV4ChargeInput {\n amount: number;\n currency: string;\n reference: string;\n customerId: string;\n paymentMethodId: string;\n recurring?: boolean;\n redirectUrl?: string;\n meta?: Record<string, unknown>;\n idempotencyKey: string;\n traceId?: string;\n}\n\nexport interface FlutterwaveV4RefundInput {\n chargeId: string;\n amount: number;\n reason: FlutterwaveV4RefundReason;\n idempotencyKey: string;\n traceId?: string;\n}\n\nexport type FlutterwaveV4RefundReason =\n | \"duplicate\"\n | \"fraudulent\"\n | \"requested_by_customer\"\n | \"expired_uncaptured_charge\";\n\nexport type FlutterwaveV4ChargeAuthorization =\n | { type: \"pin\"; pin: { nonce: string; encrypted_pin: string } }\n | { type: \"otp\"; otp: { code: string } };\n\nexport interface FlutterwaveV4Resource {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface FlutterwaveV4Adapter {\n createCustomer(input: FlutterwaveV4CustomerInput): Promise<FlutterwaveV4Resource>;\n createCardPaymentMethod(\n input: FlutterwaveV4CardPaymentMethodInput,\n ): Promise<FlutterwaveV4Resource>;\n createCharge(input: FlutterwaveV4ChargeInput): Promise<FlutterwaveV4Resource>;\n retrieveCharge(chargeId: string): Promise<FlutterwaveV4Resource>;\n updateChargeAuthorization(input: {\n chargeId: string;\n authorization: FlutterwaveV4ChargeAuthorization;\n idempotencyKey: string;\n traceId?: string;\n }): Promise<FlutterwaveV4Resource>;\n createRefund(input: FlutterwaveV4RefundInput): Promise<FlutterwaveV4Resource>;\n}\n\nconst DEFAULT_IDENTITY_URL =\n \"https://idp.flutterwave.com/realms/flutterwave/protocol/openid-connect/token\";\nconst DEFAULT_API_URL = \"https://f4bexperience.flutterwave.com\";\n\n/**\n * Create a server-only Flutterwave v4 transport. It accepts encrypted card\n * fields only; raw PAN/CVV handling belongs in a PCI-compliant client flow.\n */\nexport function createFlutterwaveV4Adapter(options: FlutterwaveV4Options): FlutterwaveV4Adapter {\n if (!options.clientId || !options.clientSecret) {\n throw new Error(\"Flutterwave v4 clientId and clientSecret are required\");\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") throw new Error(\"Fetch is not available\");\n const baseUrl = (options.apiBaseUrl ?? DEFAULT_API_URL).replace(/\\/+$/, \"\");\n const identityUrl = options.identityUrl ?? DEFAULT_IDENTITY_URL;\n const now = options.now ?? Date.now;\n let token: string | undefined;\n let refreshAt = 0;\n let tokenRequest: Promise<string> | undefined;\n\n const getToken = async (): Promise<string> => {\n if (token !== undefined && token.length > 0 && now() < refreshAt) return token;\n if (tokenRequest) return tokenRequest;\n tokenRequest = (async () => {\n const response = await fetchImpl(identityUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: options.clientId,\n client_secret: options.clientSecret,\n grant_type: \"client_credentials\",\n }),\n });\n const raw = await parseJson(response, \"authenticate\");\n const accessToken = field(raw, \"access_token\");\n const expiresIn = Number(field(raw, \"expires_in\"));\n if (!response.ok || typeof accessToken !== \"string\" || !Number.isFinite(expiresIn)) {\n throw v4Error(\"authenticate\", response.status, raw);\n }\n token = accessToken;\n // Flutterwave recommends refresh at least 60 seconds before expiry.\n refreshAt = now() + Math.max(0, expiresIn - 60) * 1_000;\n return accessToken;\n })().finally(() => {\n tokenRequest = undefined;\n });\n return tokenRequest;\n };\n\n const request = async (\n operation: string,\n path: string,\n input: {\n method?: \"GET\" | \"POST\" | \"PUT\";\n body?: unknown;\n idempotencyKey?: string;\n traceId?: string;\n } = {},\n allowAuthRetry = true,\n ): Promise<FlutterwaveV4Resource> => {\n const method = input.method ?? \"GET\";\n if (method !== \"GET\") validateIdempotencyKey(input.idempotencyKey);\n if (input.traceId !== undefined) validateTraceId(input.traceId);\n const headers = new Headers({\n accept: \"application/json\",\n authorization: `Bearer ${await getToken()}`,\n \"content-type\": \"application/json\",\n });\n if (input.idempotencyKey !== undefined) headers.set(\"x-idempotency-key\", input.idempotencyKey);\n if (input.traceId !== undefined) headers.set(\"x-trace-id\", input.traceId);\n const response = await fetchImpl(`${baseUrl}${path}`, {\n method,\n headers,\n ...(input.body === undefined ? {} : { body: JSON.stringify(input.body) }),\n });\n const raw = await parseJson(response, operation);\n if (response.status === 401 && allowAuthRetry) {\n token = undefined;\n refreshAt = 0;\n // Retry once with a fresh OAuth token; POST idempotency keys make this safe.\n return request(operation, path, input, false);\n }\n if (!response.ok) throw v4Error(operation, response.status, raw);\n const status = field(raw, \"status\");\n const data = field(raw, \"data\");\n if (status !== \"success\" || !isObject(data) || typeof data.id !== \"string\") {\n throw new Error(`Flutterwave v4 ${operation} returned an invalid response`);\n }\n return data as FlutterwaveV4Resource;\n };\n\n const withTraceId = (value?: string) => value ?? randomBytes(16).toString(\"hex\");\n\n return {\n createCustomer: async (input) => {\n const { idempotencyKey, traceId, ...body } = input;\n if (!input.email.includes(\"@\")) throw new Error(\"A valid customer email is required\");\n return request(\"create customer\", \"/customers\", {\n method: \"POST\",\n body,\n idempotencyKey,\n traceId: withTraceId(traceId),\n });\n },\n createCardPaymentMethod: async (input) => {\n const { idempotencyKey, traceId, customerId, ...card } = input;\n if (Object.values(card).some((value) => typeof value !== \"string\" || value.length === 0)) {\n throw new Error(\"Flutterwave v4 requires encrypted card fields and a nonce\");\n }\n return request(\"create payment method\", \"/payment-methods\", {\n method: \"POST\",\n body: {\n type: \"card\",\n card,\n ...(customerId !== undefined ? { customer_id: customerId } : {}),\n },\n idempotencyKey,\n traceId: withTraceId(traceId),\n });\n },\n createCharge: async (input) => {\n validateReference(input.reference);\n if (!Number.isFinite(input.amount) || input.amount < 0.01) {\n throw new Error(\"Flutterwave v4 charge amount must be at least 0.01\");\n }\n const { idempotencyKey, traceId, customerId, paymentMethodId, redirectUrl, ...charge } =\n input;\n return request(\"create charge\", \"/charges\", {\n method: \"POST\",\n body: {\n ...charge,\n customer_id: customerId,\n payment_method_id: paymentMethodId,\n ...(redirectUrl !== undefined ? { redirect_url: redirectUrl } : {}),\n },\n idempotencyKey,\n traceId: withTraceId(traceId),\n });\n },\n retrieveCharge: async (chargeId) => {\n if (!chargeId) throw new Error(\"Flutterwave v4 charge id is required\");\n return request(\"retrieve charge\", `/charges/${encodeURIComponent(chargeId)}`);\n },\n updateChargeAuthorization: async (input) => {\n if (!input.chargeId) throw new Error(\"Flutterwave v4 charge id is required\");\n return request(\n \"update charge authorization\",\n `/charges/${encodeURIComponent(input.chargeId)}`,\n {\n method: \"PUT\",\n body: { authorization: input.authorization },\n idempotencyKey: input.idempotencyKey,\n traceId: withTraceId(input.traceId),\n },\n );\n },\n createRefund: async (input) => {\n if (!input.chargeId || !isV4RefundReason(input.reason)) {\n throw new Error(\"Flutterwave v4 refund chargeId and reason are required\");\n }\n if (!Number.isFinite(input.amount) || input.amount < 0.01) {\n throw new Error(\"Flutterwave v4 refund amount must be at least 0.01\");\n }\n const { idempotencyKey, traceId, chargeId, ...refund } = input;\n return request(\"create refund\", \"/refunds\", {\n method: \"POST\",\n body: { charge_id: chargeId, ...refund },\n idempotencyKey,\n traceId: withTraceId(traceId),\n });\n },\n };\n}\n\nasync function parseJson(response: Response, operation: string): Promise<unknown> {\n try {\n return await response.json();\n } catch (cause) {\n throw new Error(`Flutterwave v4 ${operation} returned non-JSON HTTP ${response.status}`, {\n cause,\n });\n }\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction field(value: unknown, key: string): unknown {\n return isObject(value) ? value[key] : undefined;\n}\n\nfunction validateIdempotencyKey(value: string | undefined): asserts value is string {\n if (value === undefined || value.length === 0 || !/^[\\x21-\\x7E]{12,255}$/.test(value)) {\n throw new Error(\"Flutterwave v4 idempotency keys must be 12-255 printable ASCII characters\");\n }\n}\n\nfunction validateTraceId(value: string): void {\n if (!/^[\\x21-\\x7E]{12,255}$/.test(value)) {\n throw new Error(\"Flutterwave v4 trace ids must be 12-255 printable ASCII characters\");\n }\n}\n\nfunction validateReference(value: string): void {\n if (!/^[A-Za-z0-9-]{6,42}$/.test(value)) {\n throw new Error(\"Flutterwave v4 references must be 6-42 letters, digits, or hyphens\");\n }\n}\n\nfunction isV4RefundReason(value: unknown): value is FlutterwaveV4RefundReason {\n return (\n value === \"duplicate\" ||\n value === \"fraudulent\" ||\n value === \"requested_by_customer\" ||\n value === \"expired_uncaptured_charge\"\n );\n}\n\nfunction v4Error(operation: string, status: number, raw: unknown): Error {\n const message = field(field(raw, \"error\"), \"message\") ?? field(raw, \"message\");\n const error = new Error(\n typeof message === \"string\"\n ? message\n : `Flutterwave v4 ${operation} failed with HTTP ${status}`,\n );\n Object.assign(error, { status, retryable: status === 408 || status === 429 || status >= 500 });\n return error;\n}\n","import type { GenericEndpointContext } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\n\nimport type { AnyFlutterwaveOptions, Subscription } from \"./types.ts\";\nimport { createBillingStore } from \"./billing-store.ts\";\nimport { getPlanByName } from \"./utils.ts\";\n\nexport const getOrganizationSubscription = async (\n ctx: GenericEndpointContext,\n organizationId: string,\n groupId?: string | null,\n): Promise<Subscription | null> => {\n return createBillingStore(ctx).findCurrentSubscription(organizationId, groupId);\n};\n\nexport const checkSeatLimit = async (\n ctx: GenericEndpointContext,\n organizationId: string,\n seatsToAdd = 1,\n): Promise<boolean> => {\n const store = createBillingStore(ctx);\n const subscriptions = (await store.findSubscriptionsByReference(organizationId)).filter(\n (subscription) => subscription.status === \"active\" || subscription.status === \"trialing\",\n );\n const seatLimit = subscriptions.reduce<number | undefined>(\n (maximum, subscription) =>\n typeof subscription.seats === \"number\"\n ? Math.max(maximum ?? subscription.seats, subscription.seats)\n : maximum,\n undefined,\n );\n const members = await store.listMembers(organizationId);\n\n if (seatLimit === undefined) {\n return true; // No subscription, no specific limit enforcement here (or maybe allow depending on config)\n }\n\n if (members.length + seatsToAdd > seatLimit) {\n throw new APIError(\"FORBIDDEN\", {\n message: `Organization member limit reached. Used: ${members.length}, Max: ${seatLimit}`,\n });\n }\n\n return true;\n};\n\nexport async function getOrganizationEntitlements(\n ctx: GenericEndpointContext,\n organizationId: string,\n options: AnyFlutterwaveOptions,\n): Promise<{ limits: Record<string, number>; features: string[] }> {\n const subscriptions = (\n await createBillingStore(ctx).findSubscriptionsByReference(organizationId)\n ).filter(\n (subscription) => subscription.status === \"active\" || subscription.status === \"trialing\",\n );\n const limits: Record<string, number> = {};\n const features = new Set<string>();\n for (const subscription of subscriptions) {\n const plan = await getPlanByName(options, subscription.plan);\n for (const [name, value] of Object.entries(plan?.limits ?? {})) {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n limits[name] = Math.max(limits[name] ?? value, value);\n }\n }\n for (const feature of plan?.features ?? []) features.add(feature);\n }\n return { limits, features: [...features] };\n}\n\nexport const checkTeamLimit = async (\n ctx: GenericEndpointContext,\n organizationId: string,\n maxTeams: number,\n): Promise<boolean> => {\n const teams = await createBillingStore(ctx).listTeams(organizationId);\n\n if (teams.length >= maxTeams) {\n throw new APIError(\"FORBIDDEN\", {\n message: `Organization team limit reached. Max teams: ${maxTeams}`,\n });\n }\n\n return true;\n};\n","/* oxlint-disable typescript/strict-boolean-expressions, no-restricted-imports */\nimport { createHash } from \"node:crypto\";\nimport type { GenericEndpointContext } from \"better-auth\";\nimport * as z from \"zod\";\nimport { APIError } from \"better-auth/api\";\nimport { createBillingStore, type BillingStoreAdapter } from \"./billing-store.ts\";\nimport { recordVerifiedPayment } from \"./billing-lifecycle.ts\";\nimport { createFlutterwaveAdapter } from \"./flutterwave-sdk.ts\";\nimport type { FlutterwaveTransactionData } from \"./flutterwave-contracts.ts\";\nimport {\n createRenewalMetadata,\n parseFlutterwaveMetadata,\n stringifyFlutterwaveMetadata,\n} from \"./metadata.ts\";\nimport { acquireOperation, checkpointOperation, failOperation } from \"./operation-ledger.ts\";\nimport { decryptPaymentToken } from \"./token-crypto.ts\";\nimport type {\n AnyFlutterwaveOptions,\n ChargeRecurringSubscriptionInput,\n ChargeRecurringSubscriptionResult,\n FlutterwaveSyncResult,\n} from \"./types.ts\";\nimport { calculatePlanAmount } from \"./utils.ts\";\n\nfunction adapter(options: AnyFlutterwaveOptions) {\n return createFlutterwaveAdapter({\n publicKey: options.publicKey,\n secretKey: options.secretKey,\n flutterwaveClient: options.flutterwaveClient,\n fetch: options.fetch,\n apiBaseUrl: options.apiBaseUrl,\n });\n}\n\nexport async function syncFlutterwavePlans(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n): Promise<FlutterwaveSyncResult> {\n const remote = await adapter(options).listPaymentPlans();\n const store = createBillingStore(ctx);\n const now = new Date();\n for (const plan of remote) {\n await store.upsertPlanByPaymentPlanId(plan.id, {\n name: plan.name,\n amount: plan.amount,\n currency: plan.currency,\n interval: plan.interval,\n paymentPlanId: plan.id,\n reconciledAt: now,\n createdAt: now,\n updatedAt: now,\n });\n }\n return { status: \"success\", count: remote.length };\n}\n\nexport async function chargeSubscriptionRenewal(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n input: ChargeRecurringSubscriptionInput,\n): Promise<ChargeRecurringSubscriptionResult> {\n const store = createBillingStore(ctx);\n const subscription = await store.findSubscriptionById(input.subscriptionId);\n if (!subscription) throw new APIError(\"NOT_FOUND\", { message: \"Subscription not found\" });\n if (\n subscription.status === \"canceled\" ||\n subscription.endedAt != null ||\n (subscription.cancelAtPeriodEnd &&\n subscription.cancelAt &&\n new Date(subscription.cancelAt) <= new Date())\n ) {\n throw new APIError(\"BAD_REQUEST\", { message: \"Canceled subscriptions cannot be renewed\" });\n }\n if (subscription.paymentPlanId != null || subscription.subscriptionId != null) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Native subscription renewals are managed by Flutterwave\",\n });\n }\n const plan =\n (await store.findPlanByName(subscription.plan)) ??\n (await (async () => {\n const configured = options.subscription?.plans;\n const plans = typeof configured === \"function\" ? await configured() : (configured ?? []);\n return plans.find((candidate) => candidate.name === subscription.plan) ?? null;\n })());\n const amount = input.amount ?? (plan ? calculatePlanAmount(plan, subscription.seats) : undefined);\n if (\n amount === undefined ||\n !Number.isFinite(amount) ||\n amount <= 0 ||\n !plan?.currency ||\n !subscription.billingEmail\n ) {\n throw new APIError(\"BAD_REQUEST\", { message: \"Subscription billing details are incomplete\" });\n }\n if (\n input.renewalId !== undefined &&\n (input.renewalId.length === 0 || input.renewalId.length > 255)\n ) {\n throw new APIError(\"BAD_REQUEST\", { message: \"renewalId must contain 1-255 characters\" });\n }\n const priorTransaction = subscription.txRef\n ? await store.findTransactionByTxRef(subscription.txRef)\n : null;\n const priorMetadata = parseFlutterwaveMetadata(priorTransaction?.metadata);\n const priorOperationId =\n typeof priorMetadata.renewalOperationId === \"string\"\n ? priorMetadata.renewalOperationId\n : undefined;\n const priorOperation = priorOperationId ? await store.findWebhookEvent(priorOperationId) : null;\n const unfinishedPrior = priorOperation !== null && priorOperation.status !== \"processed\";\n const period =\n subscription.periodEnd == null ? \"initial\" : new Date(subscription.periodEnd).toISOString();\n const intent = input.renewalId ?? period;\n const digest = createHash(\"sha256\")\n .update(JSON.stringify([subscription.id, intent]))\n .digest(\"hex\");\n const operationId =\n input.renewalId === undefined && unfinishedPrior\n ? priorOperationId!\n : `internal:renewal:${digest}`;\n const txRef =\n input.renewalId === undefined && unfinishedPrior && priorTransaction\n ? priorTransaction.txRef\n : `flw_renewal_${digest.slice(0, 40)}`;\n if (unfinishedPrior && operationId !== priorOperationId) {\n throw new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"A previous renewal requires reconciliation before starting another intent\",\n });\n }\n const requestedOperation = await store.findWebhookEvent(operationId);\n // A completed period must not be charged again by an early scheduler invocation.\n if (\n !unfinishedPrior &&\n requestedOperation === null &&\n subscription.periodEnd != null &&\n new Date(subscription.periodEnd) > new Date()\n ) {\n throw new APIError(\"BAD_REQUEST\", { message: \"The subscription is not due for renewal\" });\n }\n let operation = await acquireOperation(store, {\n eventId: operationId,\n eventType: \"internal.subscription.renewal\",\n txRef,\n payload: JSON.stringify({ phase: \"reserved\", txRef, amount, currency: plan.currency, period }),\n });\n const progress = renewalIntentSchema.parse(JSON.parse(operation.payload));\n if (progress.amount !== amount || progress.currency !== plan.currency) {\n if (operation.status !== \"processed\") await failOperation(store, operation);\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The renewal intent amount or currency has changed\",\n });\n }\n const provider = adapter(options);\n try {\n let transaction = await store.findTransactionByTxRef(progress.txRef);\n transaction ??= await store.createTransaction({\n txRef: progress.txRef,\n referenceId: subscription.referenceId,\n userId: subscription.userId,\n amount,\n currency: plan.currency,\n status: \"pending\",\n plan: subscription.plan,\n metadata: stringifyFlutterwaveMetadata({\n ...createRenewalMetadata({\n subscriptionId: subscription.id,\n referenceId: subscription.referenceId,\n }),\n renewalOperationId: operationId,\n }),\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n if (operation.status === \"processed\") {\n // Stable renewalId retries return the same verified payment instead of creating a new charge.\n const verified = await provider.verifyTransaction({ txRef: progress.txRef });\n await recordVerifiedPayment(ctx, options, transaction, verified);\n return renewalResult(verified);\n }\n if (progress.phase === \"reserved\") {\n if (progress.period !== period)\n throw new APIError(\"BAD_REQUEST\", {\n message: \"The reserved renewal period has already changed\",\n });\n if (!subscription.encryptedPaymentToken && !input.redirectUrl) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"redirectUrl is required when the subscription has no reusable payment token\",\n });\n }\n // Persist ownership and dispatch intent before the provider call. An ambiguous outcome is never recharged.\n if (\n !(await store.updateCurrentSubscription(subscription, {\n txRef: progress.txRef,\n status: \"past_due\",\n updatedAt: new Date(),\n }))\n )\n throw new APIError(\"SERVICE_UNAVAILABLE\", {\n message: \"Subscription changed while reserving renewal; retry later\",\n });\n const token = subscription.encryptedPaymentToken\n ? await decryptPaymentToken(subscription.encryptedPaymentToken, ctx.context.secret)\n : null;\n progress.phase = \"submitted\";\n operation = await checkpointOperation(store, operation, {\n payload: JSON.stringify(progress),\n });\n if (token === null) {\n const checkout = await provider.initializePayment({\n tx_ref: progress.txRef,\n amount,\n currency: plan.currency,\n redirect_url: input.redirectUrl!,\n customer: { email: subscription.billingEmail },\n meta: parseFlutterwaveMetadata(transaction.metadata),\n });\n progress.checkoutUrl = checkout.link;\n progress.phase = \"checkout\";\n operation = await checkpointOperation(store, operation, {\n payload: JSON.stringify(progress),\n status: \"failed\",\n });\n return {\n status: \"pending\",\n data: { kind: \"checkout\", url: checkout.link, txRef: progress.txRef, redirect: true },\n };\n }\n const charged = await provider.chargeToken({\n token,\n amount,\n currency: plan.currency,\n email: subscription.billingEmail,\n tx_ref: progress.txRef,\n });\n // Persist a provider identifier before verification whenever the provider has returned one.\n transaction =\n (await store.updateTransactionByTxRef(progress.txRef, {\n transactionId: charged.id,\n updatedAt: new Date(),\n })) ?? transaction;\n const verified = await provider.verifyTransaction({ transactionId: charged.id });\n await recordVerifiedPayment(ctx, options, transaction, verified);\n operation = await checkpointOperation(store, operation, {\n status: verified.status === \"pending\" ? \"failed\" : \"processed\",\n processedAt: verified.status === \"pending\" ? undefined : new Date(),\n });\n return renewalResult(verified);\n }\n // A previous dispatch may have succeeded even if its response was lost. Query the same reference only.\n if (progress.checkoutUrl !== undefined && transaction.status === \"pending\") {\n operation = await checkpointOperation(store, operation, { status: \"failed\" });\n return {\n status: \"pending\",\n data: {\n kind: \"checkout\",\n url: progress.checkoutUrl,\n txRef: progress.txRef,\n redirect: true,\n },\n };\n }\n const verified = await provider.verifyTransaction({ txRef: progress.txRef });\n await recordVerifiedPayment(ctx, options, transaction, verified);\n operation = await checkpointOperation(store, operation, {\n status: verified.status === \"pending\" ? \"failed\" : \"processed\",\n processedAt: verified.status === \"pending\" ? undefined : new Date(),\n });\n if (verified.status === \"pending\" && progress.checkoutUrl !== undefined) {\n return {\n status: \"pending\",\n data: {\n kind: \"checkout\",\n url: progress.checkoutUrl,\n txRef: progress.txRef,\n redirect: true,\n },\n };\n }\n return renewalResult(verified);\n } catch (error) {\n if (operation.status !== \"processed\") await failOperation(store, operation);\n throw error;\n }\n}\n\nconst renewalIntentSchema = z.object({\n phase: z.enum([\"reserved\", \"submitted\", \"checkout\"]),\n txRef: z.string().min(1),\n amount: z.number().positive(),\n currency: z.string().min(1),\n period: z.string().min(1),\n checkoutUrl: z.string().optional(),\n});\n\nfunction renewalResult(verified: FlutterwaveTransactionData): ChargeRecurringSubscriptionResult {\n return {\n status:\n verified.status === \"successful\"\n ? \"success\"\n : verified.status === \"pending\"\n ? \"pending\"\n : \"failed\",\n data: {\n id: verified.id,\n txRef: verified.tx_ref,\n flwRef: verified.flw_ref ?? undefined,\n amount: verified.amount,\n chargedAmount: verified.charged_amount,\n currency: verified.currency,\n status: verified.status,\n paymentType: verified.payment_type ?? undefined,\n },\n };\n}\n\n/** Call from an independently authorized scheduled job; no browser endpoint is exposed. */\nexport async function processScheduledFlutterwaveCancellations(\n ctx: { context: { adapter: BillingStoreAdapter } },\n options: AnyFlutterwaveOptions,\n input: { now?: Date; limit?: number } = {},\n) {\n const now = input.now ?? new Date();\n const limit = input.limit ?? 100;\n if (!Number.isFinite(now.getTime()) || !Number.isInteger(limit) || limit < 1 || limit > 1000) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"A valid time and limit from 1 to 1000 are required\",\n });\n }\n const store = createBillingStore(ctx);\n const due = await store.listDueCancellations(now, limit);\n const failed: string[] = [];\n let canceled = 0;\n for (const subscription of due) {\n try {\n if (subscription.paymentPlanId != null && subscription.subscriptionId == null) {\n throw new Error(\"Native subscription has not been identified\");\n }\n if (\n subscription.subscriptionId != null &&\n subscription.status !== \"canceled\" &&\n subscription.canceledAt == null\n ) {\n await adapter(options).cancelSubscription(subscription.subscriptionId);\n }\n if (await store.completeScheduledCancellation(subscription, now)) canceled++;\n } catch {\n // Retain the schedule so the next invocation can retry without losing the cancellation.\n failed.push(subscription.id);\n }\n }\n return { canceled, failed, hasMore: due.length === limit };\n}\n\nexport async function refundFlutterwaveTransaction(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n input: { transactionId: number; amount?: number; reason?: string },\n) {\n const store = createBillingStore(ctx);\n const transaction = await store.findTransactionById(input.transactionId);\n if (!transaction) throw new APIError(\"NOT_FOUND\", { message: \"Transaction not found\" });\n const result = await adapter(options).refundTransaction(\n input.transactionId,\n input.amount,\n input.reason,\n );\n const now = new Date();\n return store.createRefund({\n refundId: result.id,\n transactionId: input.transactionId,\n txRef: transaction.txRef,\n referenceId: transaction.referenceId,\n amount: result.amount_refunded ?? result.amount ?? input.amount ?? transaction.amount,\n currency: transaction.currency,\n status: result.status,\n reason: input.reason,\n createdAt: now,\n updatedAt: now,\n });\n}\n","/* oxlint-disable no-restricted-imports, typescript/strict-boolean-expressions */\nimport type { GenericEndpointContext } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\nimport * as z from \"zod\";\nimport { createBillingStore } from \"./billing-store.ts\";\nimport { paymentMatches, recordVerifiedPayment } from \"./billing-lifecycle.ts\";\nimport { createFlutterwaveAdapter } from \"./flutterwave-sdk.ts\";\nimport type { AnyFlutterwaveOptions, FlutterwaveTransactionResponse } from \"./types.ts\";\n\nexport type FlutterwaveReconciliationSource = \"webhook\" | \"queue\" | \"admin\" | \"server\" | \"browser\";\n\nexport interface ReconcileFlutterwaveTransactionInput {\n txRef?: string;\n transactionId?: number;\n source?: FlutterwaveReconciliationSource;\n throwOnError?: boolean;\n}\n\nexport async function reconcileFlutterwaveTransaction(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n input: ReconcileFlutterwaveTransactionInput,\n) {\n const store = createBillingStore(ctx);\n const local = input.txRef\n ? await store.findTransactionByTxRef(input.txRef)\n : input.transactionId\n ? await store.findTransactionById(input.transactionId)\n : null;\n if (!local) throw new APIError(\"NOT_FOUND\", { message: \"Transaction not found\" });\n const provider = createFlutterwaveAdapter({\n publicKey: options.publicKey,\n secretKey: options.secretKey,\n flutterwaveClient: options.flutterwaveClient,\n fetch: options.fetch,\n apiBaseUrl: options.apiBaseUrl,\n });\n const verified = await provider.verifyTransaction({\n txRef: input.txRef,\n transactionId: input.transactionId,\n });\n const matches = paymentMatches(local, verified);\n if (!matches) {\n if (input.throwOnError === false) {\n return {\n ok: false as const,\n source: input.source ?? \"server\",\n txRef: local.txRef,\n error: { code: \"TRANSACTION_MISMATCH\", message: \"Transaction details do not match\" },\n };\n }\n throw new APIError(\"BAD_REQUEST\", { message: \"Transaction details do not match\" });\n }\n await recordVerifiedPayment(ctx, options, local, verified);\n const data: FlutterwaveTransactionResponse = {\n id: verified.id,\n txRef: verified.tx_ref,\n flwRef: verified.flw_ref ?? undefined,\n amount: verified.amount,\n chargedAmount: verified.charged_amount,\n currency: verified.currency,\n status: verified.status,\n paymentType: verified.payment_type ?? undefined,\n };\n return {\n ok: true as const,\n source: input.source ?? \"server\",\n txRef: local.txRef,\n status: verified.status,\n data,\n };\n}\n\nconst refundEnvelopeSchema = z.object({\n status: z.literal(\"success\"),\n data: z.object({\n id: z.coerce.number().int().positive(),\n status: z.string().min(1),\n amount_refunded: z.coerce.number().nonnegative().optional(),\n }),\n});\n\nexport async function reconcileFlutterwaveRefunds(\n ctx: GenericEndpointContext,\n options: AnyFlutterwaveOptions,\n) {\n const store = createBillingStore(ctx);\n const pending = await store.listPendingRefunds();\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const baseUrl = (options.apiBaseUrl ?? \"https://api.flutterwave.com\").replace(/\\/+$/, \"\");\n let updated = 0;\n for (const refund of pending) {\n if (!refund.refundId) continue;\n const response = await fetchImpl(`${baseUrl}/v3/refunds/${refund.refundId}`, {\n headers: { authorization: `Bearer ${options.secretKey}` },\n });\n if (!response.ok) continue;\n const parsed = refundEnvelopeSchema.safeParse(await response.json());\n if (!parsed.success || parsed.data.data.id !== refund.refundId) continue;\n await store.updateRefund(refund.id, {\n status: parsed.data.data.status,\n amount: parsed.data.data.amount_refunded ?? refund.amount,\n reconciledAt: new Date(),\n updatedAt: new Date(),\n });\n updated++;\n }\n return { status: \"success\" as const, count: updated };\n}\n","import { defineErrorCodes, type AuthContext, type BetterAuthPlugin } from \"better-auth\";\nimport {\n cancelSubscription,\n createSubscription,\n flutterwaveWebhook,\n getConfig,\n initializeTransaction,\n listPlans,\n listProducts,\n listSubscriptions,\n listTransactions,\n restoreSubscription,\n upgradeSubscription,\n verifyTransaction,\n} from \"./routes.ts\";\nimport { FLUTTERWAVE_ERROR_MESSAGES } from \"./route-modules/shared.ts\";\nimport { getSchema } from \"./schema.ts\";\nimport { PACKAGE_VERSION } from \"./version.ts\";\nimport type { AnyFlutterwaveOptions, FlutterwaveClientLike, FlutterwaveOptions } from \"./types.ts\";\n\nexport {\n createCheckoutMetadata,\n createProrationMetadata,\n createRenewalMetadata,\n getMetadataBoolean,\n getMetadataNumber,\n getMetadataString,\n hasFlutterwaveMetadata,\n parseFlutterwaveMetadata,\n stringifyFlutterwaveMetadata,\n} from \"./metadata.ts\";\nexport type { FlutterwaveMetadata } from \"./metadata.ts\";\nexport type { FlutterwaveTokenChargeInput } from \"./flutterwave-contracts.ts\";\nexport { createFlutterwaveAdapter, FlutterwaveAdapterError } from \"./flutterwave-sdk.ts\";\nexport { createFlutterwaveV4Adapter } from \"./flutterwave-v4.ts\";\nexport type {\n FlutterwaveV4Adapter,\n FlutterwaveV4ChargeAuthorization,\n FlutterwaveV4CardPaymentMethodInput,\n FlutterwaveV4ChargeInput,\n FlutterwaveV4CustomerInput,\n FlutterwaveV4Options,\n FlutterwaveV4RefundInput,\n FlutterwaveV4RefundReason,\n FlutterwaveV4Resource,\n} from \"./flutterwave-v4.ts\";\nexport type {\n FlutterwaveAdapter,\n FlutterwaveAdapterOptions,\n FlutterwaveSdkClient,\n} from \"./flutterwave-sdk.ts\";\nexport { decryptPaymentToken, encryptPaymentToken } from \"./token-crypto.ts\";\nexport { checkSeatLimit, checkTeamLimit, getOrganizationEntitlements } from \"./limits.ts\";\nexport {\n chargeSubscriptionRenewal,\n processScheduledFlutterwaveCancellations,\n refundFlutterwaveTransaction,\n syncFlutterwavePlans,\n} from \"./operations.ts\";\nexport { reconcileFlutterwaveRefunds, reconcileFlutterwaveTransaction } from \"./reconciliation.ts\";\nexport type * from \"./types.ts\";\n\ndeclare module \"better-auth\" {\n interface BetterAuthPluginRegistry<AuthOptions, Options> {\n flutterwave: { creator: typeof flutterwave };\n }\n}\n\nconst INTERNAL_ERROR_CODES: NonNullable<BetterAuthPlugin[\"$ERROR_CODES\"]> = defineErrorCodes(\n FLUTTERWAVE_ERROR_MESSAGES,\n);\n\n// Keep this as a type alias so Better Auth can infer the concrete endpoint keys\n// without adding a string index signature to every auth API.\n// oxlint-disable-next-line typescript/consistent-type-definitions\ntype FlutterwavePluginEndpoints = {\n initializeFlutterwaveTransaction: ReturnType<typeof initializeTransaction>;\n verifyFlutterwaveTransaction: ReturnType<typeof verifyTransaction>;\n listFlutterwaveTransactions: ReturnType<typeof listTransactions>;\n listFlutterwaveSubscriptions: ReturnType<typeof listSubscriptions>;\n createFlutterwaveSubscription: ReturnType<typeof createSubscription>;\n upgradeFlutterwaveSubscription: ReturnType<typeof upgradeSubscription>;\n cancelFlutterwaveSubscription: ReturnType<typeof cancelSubscription>;\n restoreFlutterwaveSubscription: ReturnType<typeof restoreSubscription>;\n listFlutterwaveProducts: ReturnType<typeof listProducts>;\n listFlutterwavePlans: ReturnType<typeof listPlans>;\n getFlutterwaveConfig: ReturnType<typeof getConfig>;\n flutterwaveWebhook: ReturnType<typeof flutterwaveWebhook>;\n};\n\ntype FlutterwavePluginInstance<O extends AnyFlutterwaveOptions> = Omit<\n BetterAuthPlugin,\n \"id\" | \"version\" | \"endpoints\" | \"schema\" | \"options\" | \"$ERROR_CODES\" | \"init\"\n> & {\n id: \"flutterwave\";\n version: typeof PACKAGE_VERSION;\n endpoints: FlutterwavePluginEndpoints;\n schema: ReturnType<typeof getSchema>;\n options: NoInfer<O>;\n $ERROR_CODES: typeof INTERNAL_ERROR_CODES;\n init: (ctx: AuthContext) => { options: Record<string, never> };\n};\n\nexport const flutterwave = <\n TFlutterwaveClient extends FlutterwaveClientLike = FlutterwaveClientLike,\n O extends FlutterwaveOptions<TFlutterwaveClient> = FlutterwaveOptions<TFlutterwaveClient>,\n>(\n options: O,\n): FlutterwavePluginInstance<O> => {\n const routeOptions = options as unknown as AnyFlutterwaveOptions;\n return {\n id: \"flutterwave\",\n version: PACKAGE_VERSION,\n endpoints: {\n initializeFlutterwaveTransaction: initializeTransaction(\n routeOptions,\n \"/flutterwave/transaction/initialize\",\n ),\n verifyFlutterwaveTransaction: verifyTransaction(\n routeOptions,\n \"/flutterwave/transaction/verify\",\n ),\n listFlutterwaveTransactions: listTransactions(routeOptions, \"/flutterwave/transaction/list\"),\n listFlutterwaveSubscriptions: listSubscriptions(\n routeOptions,\n \"/flutterwave/subscription/list\",\n ),\n createFlutterwaveSubscription: createSubscription(\n routeOptions,\n \"/flutterwave/subscription/create\",\n ),\n upgradeFlutterwaveSubscription: upgradeSubscription(\n routeOptions,\n \"/flutterwave/subscription/upgrade\",\n ),\n cancelFlutterwaveSubscription: cancelSubscription(\n routeOptions,\n \"/flutterwave/subscription/cancel\",\n ),\n restoreFlutterwaveSubscription: restoreSubscription(\n routeOptions,\n \"/flutterwave/subscription/restore\",\n ),\n listFlutterwaveProducts: listProducts(routeOptions, \"/flutterwave/product/list\"),\n listFlutterwavePlans: listPlans(routeOptions, \"/flutterwave/plan/list\"),\n getFlutterwaveConfig: getConfig(routeOptions, \"/flutterwave/config\"),\n flutterwaveWebhook: flutterwaveWebhook(routeOptions, \"/flutterwave/webhook\"),\n },\n schema: getSchema(routeOptions),\n init: (ctx) => {\n if (\n options.organization?.enabled === true &&\n ctx.options.plugins?.some((plugin) => plugin.id === \"organization\") !== true\n ) {\n ctx.logger.error(\n \"Flutterwave organization billing requires the Better Auth organization plugin.\",\n );\n }\n return { options: {} };\n },\n $ERROR_CODES: INTERNAL_ERROR_CODES,\n options,\n };\n};\n"],"mappings":";;;;;;;;AAkHA,SAAS,4BACP,eAC2B;CAC3B,MAAM,6BAAa,IAAI,IAAI;EACzB,CAAC,UAAU,CAAC;EACZ,CAAC,YAAY,CAAC;EACd,CAAC,cAAc,CAAC;EAChB,CAAC,YAAY,CAAC;EACd,CAAC,YAAY,CAAC;CAChB,CAAC;CACD,OAAO,CAAC,GAAG,aAAa,CAAC,CAAC,MAAM,GAAG,MAAM;EACvC,MAAM,oBAAoB,WAAW,IAAI,EAAE,MAAM,KAAK,OAAO,WAAW,IAAI,EAAE,MAAM,KAAK;EACzF,OAAO,qBAAqB,IACxB,mBACA,IAAI,KAAK,EAAE,SA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