UNPKG

autumn-js

Version:
398 lines (391 loc) 11.3 kB
import { getIdentityContext, getOrganizationContext, scopeContainsOrg } from "./chunk-SRJD6EXQ.mjs"; import { secretKeyCheck } from "./chunk-UNZHJTEY.mjs"; import { createRouterWithOptions } from "./chunk-4MEEJLXG.mjs"; import "./chunk-PO4EL4BW.mjs"; import "./chunk-MHIUO3ST.mjs"; import "./chunk-USQ76FYI.mjs"; import "./chunk-LOSIWWM2.mjs"; import "./chunk-35N7BIAE.mjs"; import { Autumn, CustomerExpandEnum, QueryRangeEnum } from "./chunk-QOJMX7ML.mjs"; import "./chunk-2TEL6LR5.mjs"; import "./chunk-KSG3E4Q2.mjs"; // src/libraries/backend/better-auth.ts import { getSessionFromCtx } from "better-auth/api"; import { createAuthEndpoint } from "better-auth/plugins"; import { APIError, createEndpoint } from "better-call"; import { findRoute } from "rou3"; import { z as z5 } from "zod/v4"; // src/libraries/react/client/types/clientAttachTypes.ts import { z } from "zod/v4"; var AttachFeatureOptionsSchema = z.object({ featureId: z.string(), quantity: z.number() }); var AttachParamsSchema = z.object({ productId: z.string().optional(), entityId: z.string().optional(), options: z.array(AttachFeatureOptionsSchema).optional(), productIds: z.array(z.string()).optional(), freeTrial: z.boolean().optional(), successUrl: z.string().optional(), metadata: z.record(z.string(), z.string()).optional(), forceCheckout: z.boolean().optional(), /** * @deprecated This field is deprecated and will be removed in a future version. */ dialog: z.any().optional().describe( "DEPRECATED: This field is deprecated and will be removed in a future version. Please use the checkout() method instead." ), entityData: z.any().optional(), openInNewTab: z.boolean().optional(), reward: z.string().optional(), checkoutSessionParams: z.record(z.string(), z.any()).optional() }); var CheckoutParamsSchema = z.object({ productId: z.string().optional(), productIds: z.array(z.string()).optional(), entityId: z.string().optional(), entityData: z.any().optional(), options: z.array(AttachFeatureOptionsSchema).optional(), successUrl: z.string().optional(), openInNewTab: z.boolean().optional(), dialog: z.any().optional(), forceCheckout: z.boolean().optional(), checkoutSessionParams: z.record(z.string(), z.any()).optional(), reward: z.string().optional() }); // src/libraries/react/client/types/clientEntTypes.ts import { z as z2 } from "zod/v4"; var CreateEntityParamsSchema = z2.object({ id: z2.string(), name: z2.string().optional(), featureId: z2.string() }); var GetEntityParamsSchema = z2.object({ expand: z2.array(z2.string()).optional() }); var EntityDataParamsSchema = z2.object({ name: z2.string().optional(), featureId: z2.string() }); // src/libraries/react/client/types/clientGenTypes.ts import { z as z3 } from "zod/v4"; var CancelParamsSchema = z3.object({ productId: z3.string(), entityId: z3.string().optional(), cancelImmediately: z3.boolean().optional() }); var CheckParamsSchema = z3.object({ featureId: z3.string().optional(), productId: z3.string().optional(), entityId: z3.string().optional(), requiredBalance: z3.number().optional(), sendEvent: z3.boolean().optional(), withPreview: z3.boolean().optional(), dialog: z3.any().optional(), entityData: z3.any().optional(), properties: z3.record(z3.string(), z3.any()).optional() }); var TrackParamsSchema = z3.object({ featureId: z3.string().optional(), eventName: z3.string().optional(), entityId: z3.string().optional(), value: z3.number().optional(), idempotencyKey: z3.string().optional(), entityData: z3.any().optional() }); var OpenBillingPortalParamsSchema = z3.object({ returnUrl: z3.string().optional(), openInNewTab: z3.boolean().optional() }); var SetupPaymentParamsSchema = z3.object({ successUrl: z3.string().optional(), checkoutSessionParams: z3.record(z3.string(), z3.any()).optional(), openInNewTab: z3.boolean().optional() }); var QueryParamsSchema = z3.object({ featureId: z3.string().or(z3.array(z3.string())), range: QueryRangeEnum.optional() }); // src/libraries/react/client/types/clientReferralTypes.ts import { z as z4 } from "zod/v4"; var CreateReferralCodeParamsSchema = z4.object({ programId: z4.string() }); var RedeemReferralCodeParamsSchema = z4.object({ code: z4.string() }); // src/libraries/backend/better-auth.ts var router = createRouterWithOptions(); var betterAuthPathMap = { // "create-customer": "customers", // "customers/get": "customers", checkout: "checkout", attach: "attach", check: "check", track: "track", cancel: "cancel", "referrals/redeem-code": "referrals/redeem", "referrals/create-code": "referrals/code", "open-billing-portal": "billing_portal" // "products/list": "products", }; var handleReq = async ({ ctx, options, method }) => { const { found, error: resError } = secretKeyCheck(); if (!found && !options?.secretKey) { throw new APIError(resError?.statusCode ?? "BAD_REQUEST", { message: resError?.message ?? "Unknown error", code: resError?.code ?? "unknown_error" }); } const client = new Autumn({ url: options?.url, secretKey: options?.secretKey }); let searchParams = {}; try { const req = ctx.request; const url = new URL(req.url); searchParams = Object.fromEntries(url.searchParams); } catch (_) { } const rest = ctx.path.split("/autumn/")[1]; const pathname = `/api/autumn/${betterAuthPathMap[rest] || rest}`; const match = findRoute(router, method, pathname); if (!match) return ctx.json({ error: "Not found" }, { status: 404 }); const { data } = match; const { handler } = data; const body = ctx.body; const params = ctx.params; let identify; const orgContext = await getOrganizationContext(ctx, options); const finalSession = await getSessionFromCtx(ctx); let identity = null; if (options?.identify) { identity = await getIdentityContext({ orgContext, options, session: finalSession }); } if (options?.identify) { identify = () => identity; } else { identify = () => { if (!finalSession) return; if (scopeContainsOrg({ options })) { if (orgContext.activeOrganization?.id) { return { customerId: orgContext.activeOrganization?.id, customerData: { email: orgContext.activeOrganizationEmail, name: orgContext.activeOrganization?.name ?? "" } }; } else { if (options?.customerScope === "user_and_organization") { return { customerId: finalSession.user.id, customerData: { email: finalSession.user.email, name: finalSession.user.name } }; } else return null; } } else { return { customerId: finalSession.user.id, customerData: { email: finalSession.user.email, name: finalSession.user.name } }; } }; } const result = await handler({ autumn: client, body, path: pathname, getCustomer: identify, pathParams: params, searchParams }); if (result.statusCode >= 400) { throw new APIError(result.statusCode, { message: result.body.message ?? "Unknown error", code: result.body.code ?? "unknown_error" }); } return ctx.json(result.body, { status: result.statusCode }); }; var autumn = (options) => { return { id: "autumn", endpoints: { createCustomer: createEndpoint( "/autumn/customers", { method: "POST", use: [], body: z5.object({ errorOnNotFound: z5.boolean().optional(), expand: z5.array(CustomerExpandEnum).optional() }), metadata: { isAction: false } }, async (ctx) => await handleReq({ ctx, options, method: "POST" }) ), listProducts: createAuthEndpoint( "/autumn/products", { method: "GET", use: [] }, async (ctx) => await handleReq({ ctx, options, method: "GET" }) ), checkout: createAuthEndpoint( "/autumn/checkout", { method: "POST", use: [], body: CheckoutParamsSchema }, async (ctx) => { console.log("Body: ", ctx.body); return await handleReq({ ctx, options, method: "POST" }); } ), attach: createAuthEndpoint( "/autumn/attach", { method: "POST", use: [], body: AttachParamsSchema }, async (ctx) => await handleReq({ ctx, options, method: "POST" }) ), check: createAuthEndpoint( "/autumn/check", { method: "POST", use: [], body: CheckParamsSchema }, async (ctx) => { return await handleReq({ ctx, options, method: "POST" }); } ), track: createAuthEndpoint( "/autumn/track", { method: "POST", use: [], body: TrackParamsSchema }, async (ctx) => { return await handleReq({ ctx, options, method: "POST" }); } ), cancel: createAuthEndpoint( "/autumn/cancel", { method: "POST", use: [], body: CancelParamsSchema }, async (ctx) => await handleReq({ ctx, options, method: "POST" }) ), createReferralCode: createAuthEndpoint( "/autumn/referrals/code", { method: "POST", use: [], body: CreateReferralCodeParamsSchema }, async (ctx) => { return await handleReq({ ctx, options, method: "POST" }); } ), redeemReferralCode: createAuthEndpoint( "/autumn/referrals/redeem", { method: "POST", use: [], body: RedeemReferralCodeParamsSchema }, async (ctx) => { return await handleReq({ ctx, options, method: "POST" }); } ), billingPortal: createAuthEndpoint( "/autumn/billing_portal", { method: "POST", use: [], body: OpenBillingPortalParamsSchema, metadata: { isAction: false } }, async (ctx) => { return await handleReq({ ctx, options, method: "POST" }); } ), createEntity: createAuthEndpoint( "/autumn/entities", { method: "POST", use: [], body: CreateEntityParamsSchema }, async (ctx) => { return await handleReq({ ctx, options, method: "POST" }); } ), getEntity: createAuthEndpoint( "/autumn/entities/:entityId", { method: "GET", use: [] }, async (ctx) => { return await handleReq({ ctx, options, method: "GET" }); } ), deleteEntity: createAuthEndpoint( "/autumn/entities/:entityId", { method: "DELETE", use: [] }, async (ctx) => await handleReq({ ctx, options, method: "DELETE" }) ) } }; }; export { autumn };