better-auth-streampay 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as StreamPayClient } from './streampay-CYAHE6Qj.cjs';
2
- export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutOptions, d as CheckoutParams, e as ClaimExistingConsumerBy, f as ClaimExistingConsumerIdentifier, g as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, h as PluginAdapter, i as PortalOptions, R as REFERENCE_ID_METADATA_KEY, j as REFERENCE_TYPE_METADATA_KEY, k as ResolvedPlans, l as STREAMPAY_EVENT_TYPES, m as STREAMPAY_INVOICE_EVENT_TYPES, n as STREAMPAY_PAYMENT_EVENT_TYPES, o as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, p as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, q as SUBSCRIPTION_ROW_ID_METADATA_KEY, r as StreamPayCustomFieldDefinition, t as StreamPayCustomFieldsSchema, u as StreamPayEndpoints, v as StreamPayEntityType, S as StreamPayErrorCode, w as StreamPayEventType, x as StreamPayHookContext, y as StreamPayInvoiceEventType, z as StreamPayOptions, B as StreamPayPaymentEventType, G as StreamPayPaymentLinkEventType, H as StreamPayPlan, I as StreamPayPlanLike, J as StreamPayPlugin, K as StreamPayPluginRegistry, M as StreamPayPlugins, N as StreamPayProduct, O as StreamPaySubscriptionEventType, Q as StreamPayWebhookData, T as StreamPayWebhookEnvelope, U as StreamPayWebhookPayload, V as Subscription, W as SubscriptionBillingStatus, X as SubscriptionCallback, Y as SubscriptionCallbackData, Z as SubscriptionCallbacks, _ as SubscriptionReferenceType, a0 as SubscriptionStatus, a1 as SubscriptionsOptions, a2 as SyncContext, a3 as TrialEligibilityContext, a4 as WebhookEnvelopeHandler, a5 as WebhookHandler, a6 as WebhookHandlers, a7 as WebhookSyncFailure, a8 as WebhooksOptions, a9 as admin, aa as checkLimit, ab as checkout, ac as classifyWebhookFailure, ad as dispatchWebhook, ae as hasFeature, af as hasSubscriptionAccess, ag as isKnownStreamPayWebhookPayload, ah as isStreamPayWebhookEnvelope, ai as mapToErrorCode, aj as portal, s as streampay, ak as subscriptionSlotKey, al as subscriptions, am as syncWebhookPayload, an as webhooks } from './streampay-CYAHE6Qj.cjs';
1
+ import { a as StreamPayClient } from './streampay-DTuEbhQ9.cjs';
2
+ export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySubscriptionEventType, V as StreamPayWebhookData, W as StreamPayWebhookEnvelope, X as StreamPayWebhookPayload, Y as Subscription, Z as SubscriptionBillingStatus, _ as SubscriptionCallback, a0 as SubscriptionCallbackData, a1 as SubscriptionCallbacks, a2 as SubscriptionReferenceType, a3 as SubscriptionStatus, a4 as SubscriptionsOptions, a5 as SyncContext, a6 as TrialEligibilityContext, a7 as WebhookEnvelopeHandler, a8 as WebhookHandler, a9 as WebhookHandlers, aa as WebhookSyncFailure, ab as WebhooksOptions, ac as admin, ad as checkLimit, ae as checkout, af as classifyWebhookFailure, ag as dispatchWebhook, ah as hasFeature, ai as hasSubscriptionAccess, aj as isKnownStreamPayWebhookPayload, ak as isStreamPayWebhookEnvelope, al as mapToErrorCode, am as portal, s as streampay, an as subscriptionSlotKey, ao as subscriptions, ap as syncWebhookPayload, aq as webhooks } from './streampay-DTuEbhQ9.cjs';
3
3
  import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as StreamPayClient } from './streampay-CYAHE6Qj.js';
2
- export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutOptions, d as CheckoutParams, e as ClaimExistingConsumerBy, f as ClaimExistingConsumerIdentifier, g as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, h as PluginAdapter, i as PortalOptions, R as REFERENCE_ID_METADATA_KEY, j as REFERENCE_TYPE_METADATA_KEY, k as ResolvedPlans, l as STREAMPAY_EVENT_TYPES, m as STREAMPAY_INVOICE_EVENT_TYPES, n as STREAMPAY_PAYMENT_EVENT_TYPES, o as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, p as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, q as SUBSCRIPTION_ROW_ID_METADATA_KEY, r as StreamPayCustomFieldDefinition, t as StreamPayCustomFieldsSchema, u as StreamPayEndpoints, v as StreamPayEntityType, S as StreamPayErrorCode, w as StreamPayEventType, x as StreamPayHookContext, y as StreamPayInvoiceEventType, z as StreamPayOptions, B as StreamPayPaymentEventType, G as StreamPayPaymentLinkEventType, H as StreamPayPlan, I as StreamPayPlanLike, J as StreamPayPlugin, K as StreamPayPluginRegistry, M as StreamPayPlugins, N as StreamPayProduct, O as StreamPaySubscriptionEventType, Q as StreamPayWebhookData, T as StreamPayWebhookEnvelope, U as StreamPayWebhookPayload, V as Subscription, W as SubscriptionBillingStatus, X as SubscriptionCallback, Y as SubscriptionCallbackData, Z as SubscriptionCallbacks, _ as SubscriptionReferenceType, a0 as SubscriptionStatus, a1 as SubscriptionsOptions, a2 as SyncContext, a3 as TrialEligibilityContext, a4 as WebhookEnvelopeHandler, a5 as WebhookHandler, a6 as WebhookHandlers, a7 as WebhookSyncFailure, a8 as WebhooksOptions, a9 as admin, aa as checkLimit, ab as checkout, ac as classifyWebhookFailure, ad as dispatchWebhook, ae as hasFeature, af as hasSubscriptionAccess, ag as isKnownStreamPayWebhookPayload, ah as isStreamPayWebhookEnvelope, ai as mapToErrorCode, aj as portal, s as streampay, ak as subscriptionSlotKey, al as subscriptions, am as syncWebhookPayload, an as webhooks } from './streampay-CYAHE6Qj.js';
1
+ import { a as StreamPayClient } from './streampay-DTuEbhQ9.js';
2
+ export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySubscriptionEventType, V as StreamPayWebhookData, W as StreamPayWebhookEnvelope, X as StreamPayWebhookPayload, Y as Subscription, Z as SubscriptionBillingStatus, _ as SubscriptionCallback, a0 as SubscriptionCallbackData, a1 as SubscriptionCallbacks, a2 as SubscriptionReferenceType, a3 as SubscriptionStatus, a4 as SubscriptionsOptions, a5 as SyncContext, a6 as TrialEligibilityContext, a7 as WebhookEnvelopeHandler, a8 as WebhookHandler, a9 as WebhookHandlers, aa as WebhookSyncFailure, ab as WebhooksOptions, ac as admin, ad as checkLimit, ae as checkout, af as classifyWebhookFailure, ag as dispatchWebhook, ah as hasFeature, ai as hasSubscriptionAccess, aj as isKnownStreamPayWebhookPayload, ak as isStreamPayWebhookEnvelope, al as mapToErrorCode, am as portal, s as streampay, an as subscriptionSlotKey, ao as subscriptions, ap as syncWebhookPayload, aq as webhooks } from './streampay-DTuEbhQ9.js';
3
3
  import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod';
package/dist/index.js CHANGED
@@ -20,6 +20,8 @@ var $ERROR_CODES = defineErrorCodes({
20
20
  FORBIDDEN: "You do not have permission to perform this action.",
21
21
  NOT_FOUND: "The requested resource was not found.",
22
22
  CONSUMER_DUPLICATE: "A consumer with one of the provided identifiers already exists.",
23
+ STREAMPAY_CONSUMER_LINK_CONFLICT: "This StreamPay consumer is already linked to another account.",
24
+ STREAMPAY_CONSUMER_LINK_WRITE_FAILED: "The StreamPay consumer link could not be saved.",
23
25
  CONSUMER_HAS_ONGOING_ACTIVITY: "The consumer has ongoing invoices or active subscriptions and cannot be modified.",
24
26
  INVOICE_INVALID_STATE: "The invoice is in a state that forbids this action.",
25
27
  PAYMENT_DUPLICATE: "A payment with the same information already exists.",
@@ -31,6 +33,7 @@ var $ERROR_CODES = defineErrorCodes({
31
33
  PAYMENT_METHOD_INVALID: "The supplied payment method is invalid for this flow.",
32
34
  PRODUCT_LOCKED: "The product is referenced by a finalized invoice and cannot be modified.",
33
35
  COUPON_LOCKED: "The coupon is referenced by a finalized invoice and cannot be modified.",
36
+ CHECKOUT_CLIENT_FIELDS_FORBIDDEN: "Checkout fields must be resolved by the server.",
34
37
  SUBSCRIPTION_NOT_FOUND: "The subscription does not exist.",
35
38
  SUBSCRIPTION_PLAN_NOT_FOUND: "The requested subscription plan is not configured.",
36
39
  SUBSCRIPTION_ALREADY_ACTIVE: "An active subscription already exists for this plan group.",
@@ -342,12 +345,17 @@ async function ensureConsumerForUser(options, ctx, user) {
342
345
  if (isDuplicateConsumerError(err)) {
343
346
  const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
344
347
  if (reusedId) {
348
+ await assertConsumerUnclaimed(ctx, reusedId, user.id);
345
349
  try {
346
350
  await options.client.updateConsumer(reusedId, { external_id: user.id });
347
351
  } catch (backfillErr) {
348
352
  getLogger(ctx).error(
349
353
  `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
350
354
  );
355
+ throw new APIError("INTERNAL_SERVER_ERROR", {
356
+ code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
357
+ message: "StreamPay consumer linking failed. Please try again."
358
+ });
351
359
  }
352
360
  await persistConsumerId(ctx, user.id, reusedId);
353
361
  return { consumerId: reusedId, created: false };
@@ -361,7 +369,40 @@ async function ensureConsumerForUser(options, ctx, user) {
361
369
  });
362
370
  }
363
371
  }
372
+ function consumerLinkUnavailable() {
373
+ return new APIError("INTERNAL_SERVER_ERROR", {
374
+ code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
375
+ message: "StreamPay consumer linking failed. Please try again."
376
+ });
377
+ }
378
+ async function findConsumerOwner(ctx, consumerId) {
379
+ try {
380
+ return await ctx.context.adapter.findOne({
381
+ model: "user",
382
+ where: [{ field: "streampayConsumerId", value: consumerId }]
383
+ });
384
+ } catch (err) {
385
+ getLogger(ctx).error(
386
+ `consumer ownership check failed for consumer=${consumerId}: ${formatStreamPayError(err)}`
387
+ );
388
+ throw consumerLinkUnavailable();
389
+ }
390
+ }
391
+ async function assertConsumerUnclaimed(ctx, consumerId, userId) {
392
+ const owner = await findConsumerOwner(ctx, consumerId);
393
+ if (!owner) return;
394
+ if (typeof owner.id !== "string") {
395
+ getLogger(ctx).error(`consumer ownership check returned a user without an id: ${consumerId}`);
396
+ throw consumerLinkUnavailable();
397
+ }
398
+ if (owner.id === userId) return;
399
+ throw new APIError("CONFLICT", {
400
+ code: "STREAMPAY_CONSUMER_LINK_CONFLICT",
401
+ message: "This StreamPay consumer is already linked to another account."
402
+ });
403
+ }
364
404
  async function persistConsumerId(ctx, userId, consumerId) {
405
+ await assertConsumerUnclaimed(ctx, consumerId, userId);
365
406
  try {
366
407
  await ctx.context.internalAdapter.updateUser(userId, {
367
408
  streampayConsumerId: consumerId
@@ -370,6 +411,8 @@ async function persistConsumerId(ctx, userId, consumerId) {
370
411
  getLogger(ctx).error(
371
412
  `consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
372
413
  );
414
+ await assertConsumerUnclaimed(ctx, consumerId, userId);
415
+ throw consumerLinkUnavailable();
373
416
  }
374
417
  }
375
418
 
@@ -2357,15 +2400,15 @@ var admin = (adminOptions = {}) => (options, registry) => {
2357
2400
  var RelativeOrAbsoluteUrl = z.string().refine((val) => val.startsWith("/") || URL.canParse(val), {
2358
2401
  message: "Must be a valid URL or a relative path starting with /"
2359
2402
  });
2360
- var CheckoutBody = z.object({
2403
+ var CheckoutRequestBody = z.object({
2361
2404
  products: z.union([
2362
2405
  z.array(
2363
2406
  z.object({
2364
2407
  productId: z.string().uuid(),
2365
2408
  quantity: z.number().int().positive().optional()
2366
2409
  })
2367
- ).nonempty("`products` must contain at least one item."),
2368
- z.array(z.string().uuid()).nonempty("`products` must contain at least one item."),
2410
+ ).min(1, "`products` must contain at least one item."),
2411
+ z.array(z.string().uuid()).min(1, "`products` must contain at least one item."),
2369
2412
  z.string().uuid()
2370
2413
  ]).optional(),
2371
2414
  slug: z.string().optional(),
@@ -2379,10 +2422,26 @@ var CheckoutBody = z.object({
2379
2422
  validUntil: z.string().datetime().optional(),
2380
2423
  couponIds: z.array(z.string().uuid()).optional(),
2381
2424
  redirect: z.coerce.boolean().optional()
2382
- }).refine((data) => data.slug !== void 0 || data.products !== void 0, {
2383
- message: "Either `slug` or `products` is required.",
2384
- path: ["products"]
2385
2425
  });
2426
+ var CheckoutBody = CheckoutRequestBody.refine(
2427
+ (data) => data.slug !== void 0 || data.products !== void 0,
2428
+ {
2429
+ message: "Either `slug` or `products` is required.",
2430
+ path: ["products"]
2431
+ }
2432
+ );
2433
+ var SERVER_ONLY_CHECKOUT_FIELDS = [
2434
+ "products",
2435
+ "slug",
2436
+ "name",
2437
+ "description",
2438
+ "metadata",
2439
+ "successUrl",
2440
+ "failureUrl",
2441
+ "maxNumberOfPayments",
2442
+ "validUntil",
2443
+ "couponIds"
2444
+ ];
2386
2445
  function buildItem(productId, quantity) {
2387
2446
  return {
2388
2447
  product_id: productId,
@@ -2407,6 +2466,69 @@ async function resolveProducts(body, options) {
2407
2466
  (entry) => typeof entry === "string" ? buildItem(entry, 1) : buildItem(entry.productId, entry.quantity ?? 1)
2408
2467
  );
2409
2468
  }
2469
+ function rejectUntrustedClientFields(body) {
2470
+ const supplied = SERVER_ONLY_CHECKOUT_FIELDS.filter(
2471
+ (field) => Object.hasOwn(body, field) && body[field] !== void 0
2472
+ );
2473
+ if (supplied.length === 0) return;
2474
+ throw new APIError("BAD_REQUEST", {
2475
+ code: "CHECKOUT_CLIENT_FIELDS_FORBIDDEN",
2476
+ message: "Checkout product and payment fields must be resolved by the server."
2477
+ });
2478
+ }
2479
+ function mergeCheckoutOverrides(body, overrides) {
2480
+ const effective = { ...body };
2481
+ if (overrides.products !== void 0) {
2482
+ effective.products = overrides.products;
2483
+ delete effective.slug;
2484
+ }
2485
+ if (overrides.name !== void 0) effective.name = overrides.name;
2486
+ if (overrides.description !== void 0) effective.description = overrides.description;
2487
+ if (overrides.successUrl !== void 0) effective.successUrl = overrides.successUrl;
2488
+ if (overrides.failureUrl !== void 0) effective.failureUrl = overrides.failureUrl;
2489
+ if (overrides.maxNumberOfPayments !== void 0) {
2490
+ effective.maxNumberOfPayments = overrides.maxNumberOfPayments;
2491
+ }
2492
+ if (overrides.validUntil !== void 0) effective.validUntil = overrides.validUntil;
2493
+ if (overrides.couponIds !== void 0) effective.couponIds = overrides.couponIds;
2494
+ if (overrides.referenceId !== void 0) effective.referenceId = overrides.referenceId;
2495
+ if (overrides.metadata !== void 0) {
2496
+ effective.metadata = { ...body.metadata ?? {}, ...overrides.metadata };
2497
+ }
2498
+ return effective;
2499
+ }
2500
+ function validateEffectiveCheckout(body, logger2) {
2501
+ const parsed = CheckoutBody.safeParse(body);
2502
+ if (parsed.success) return parsed.data;
2503
+ const invalidPaths = [
2504
+ ...new Set(
2505
+ parsed.error.issues.map((issue) => issue.path.length > 0 ? issue.path.join(".") : "<root>")
2506
+ )
2507
+ ].join(", ");
2508
+ logger2.error(`resolved checkout validation failed at: ${invalidPaths}`);
2509
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2510
+ message: "Checkout resolution produced invalid parameters."
2511
+ });
2512
+ }
2513
+ function checkoutUser(rawUser, user) {
2514
+ if (!user || rawUser === null || typeof rawUser !== "object") return null;
2515
+ return { ...rawUser, ...user };
2516
+ }
2517
+ async function deactivatePaymentLinkBestEffort(client, paymentLinkId, logger2) {
2518
+ if (!client.updatePaymentLinkStatus) {
2519
+ logger2.error(
2520
+ `checkout compensation unavailable for payment_link=${paymentLinkId}: client does not implement updatePaymentLinkStatus`
2521
+ );
2522
+ return;
2523
+ }
2524
+ try {
2525
+ await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
2526
+ } catch (err) {
2527
+ logger2.error(
2528
+ `checkout compensation failed for payment_link=${paymentLinkId}: ${formatStreamPayError(err)}`
2529
+ );
2530
+ }
2531
+ }
2410
2532
  function resolveRedirectUrl(urlOrPath, request, baseURL) {
2411
2533
  if (!urlOrPath) return void 0;
2412
2534
  return new URL(urlOrPath, request?.url ?? baseURL).toString();
@@ -2416,99 +2538,157 @@ async function resolveConsumerId(options, ctx, user) {
2416
2538
  const { consumerId } = await ensureConsumerForUser(options, ctx, user);
2417
2539
  return consumerId;
2418
2540
  }
2419
- var checkout = (checkoutOptions = {}) => (options) => {
2420
- const client = options.client;
2421
- return {
2422
- endpoints: {
2423
- checkout: createAuthEndpoint(
2424
- "/checkout",
2425
- {
2426
- method: "POST",
2427
- body: CheckoutBody
2428
- },
2429
- async (ctx) => {
2430
- const session = await getSessionFromCtx(ctx);
2431
- const sessionUser = asSessionUser(session?.user);
2432
- if (checkoutOptions.authenticatedUsersOnly) {
2433
- if (!sessionUser) {
2434
- throw new APIError("UNAUTHORIZED", {
2435
- message: "You must be logged in to checkout."
2436
- });
2541
+ var checkout = (checkoutOptions = {}) => {
2542
+ return (options) => {
2543
+ const client = options.client;
2544
+ return {
2545
+ endpoints: {
2546
+ checkout: createAuthEndpoint(
2547
+ "/checkout",
2548
+ {
2549
+ method: "POST",
2550
+ body: checkoutOptions.resolveCheckout ? CheckoutRequestBody : CheckoutBody
2551
+ },
2552
+ async (ctx) => {
2553
+ const session = await getSessionFromCtx(ctx);
2554
+ const sessionUser = asSessionUser(session?.user);
2555
+ const user = checkoutUser(session?.user, sessionUser);
2556
+ if (checkoutOptions.authenticatedUsersOnly) {
2557
+ if (!sessionUser) {
2558
+ throw new APIError("UNAUTHORIZED", {
2559
+ message: "You must be logged in to checkout."
2560
+ });
2561
+ }
2562
+ if (sessionUser.isAnonymous) {
2563
+ throw new APIError("UNAUTHORIZED", {
2564
+ message: "Anonymous users cannot checkout."
2565
+ });
2566
+ }
2437
2567
  }
2438
- if (sessionUser.isAnonymous) {
2439
- throw new APIError("UNAUTHORIZED", {
2440
- message: "Anonymous users cannot checkout."
2441
- });
2568
+ if (checkoutOptions.resolveCheckout) {
2569
+ rejectUntrustedClientFields(ctx.body);
2442
2570
  }
2443
- }
2444
- const items = await resolveProducts(ctx.body, checkoutOptions);
2445
- const consumerId = await resolveConsumerId(options, ctx, sessionUser);
2446
- const successUrl = resolveRedirectUrl(
2447
- ctx.body.successUrl ?? checkoutOptions.successUrl,
2448
- ctx.request,
2449
- ctx.context.baseURL
2450
- );
2451
- const failureUrl = resolveRedirectUrl(
2452
- ctx.body.failureUrl ?? checkoutOptions.failureUrl,
2453
- ctx.request,
2454
- ctx.context.baseURL
2455
- );
2456
- const customMetadata = (() => {
2457
- const base = ctx.body.metadata ?? {};
2458
- const merged = ctx.body.referenceId ? { referenceId: ctx.body.referenceId, ...base } : base;
2459
- return Object.keys(merged).length > 0 ? merged : null;
2460
- })();
2461
- const payload = {
2462
- name: ctx.body.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
2463
- description: ctx.body.description ?? null,
2464
- currency: checkoutOptions.currency ?? "SAR",
2465
- items
2466
- };
2467
- if (consumerId !== null) payload.organization_consumer_id = consumerId;
2468
- if (successUrl) payload.success_redirect_url = successUrl;
2469
- if (failureUrl) payload.failure_redirect_url = failureUrl;
2470
- if (ctx.body.maxNumberOfPayments !== void 0) {
2471
- payload.max_number_of_payments = ctx.body.maxNumberOfPayments;
2472
- }
2473
- if (ctx.body.validUntil !== void 0) {
2474
- payload.valid_until = ctx.body.validUntil;
2475
- }
2476
- if (ctx.body.couponIds && ctx.body.couponIds.length > 0) {
2477
- payload.coupons = ctx.body.couponIds;
2478
- }
2479
- if (customMetadata !== null) payload.custom_metadata = customMetadata;
2480
- if (checkoutOptions.customFields) {
2481
- payload.custom_fields = checkoutOptions.customFields;
2482
- }
2483
- if (checkoutOptions.contactInformationType) {
2484
- payload.contact_information_type = checkoutOptions.contactInformationType;
2485
- }
2486
- try {
2487
- const link = await client.createPaymentLink(payload);
2488
- const url = client.getPaymentUrl(link);
2489
- if (!url) {
2490
- throw new APIError("INTERNAL_SERVER_ERROR", {
2491
- message: "StreamPay payment link created but no URL was returned."
2492
- });
2571
+ let effective = ctx.body;
2572
+ if (checkoutOptions.resolveCheckout) {
2573
+ let overrides;
2574
+ try {
2575
+ overrides = await checkoutOptions.resolveCheckout({ user, body: ctx.body }, ctx);
2576
+ } catch (err) {
2577
+ if (err instanceof APIError) throw err;
2578
+ getLogger(ctx).error(`resolveCheckout failed: ${formatStreamPayError(err)}`);
2579
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2580
+ message: "Checkout resolution failed."
2581
+ });
2582
+ }
2583
+ effective = mergeCheckoutOverrides(ctx.body, overrides);
2493
2584
  }
2494
- return ctx.json({
2495
- url,
2496
- id: link.id ?? null,
2497
- redirect: ctx.body.redirect ?? true
2498
- });
2499
- } catch (err) {
2500
- toAPIError(
2501
- {
2502
- logPrefix: "checkout creation failed:",
2503
- userMessage: "StreamPay checkout creation failed."
2504
- },
2505
- err,
2506
- getLogger(ctx)
2585
+ effective = validateEffectiveCheckout(effective, getLogger(ctx));
2586
+ const items = await resolveProducts(effective, checkoutOptions);
2587
+ const consumerId = await resolveConsumerId(options, ctx, sessionUser);
2588
+ const successUrl = resolveRedirectUrl(
2589
+ effective.successUrl ?? checkoutOptions.successUrl,
2590
+ ctx.request,
2591
+ ctx.context.baseURL
2507
2592
  );
2593
+ const failureUrl = resolveRedirectUrl(
2594
+ effective.failureUrl ?? checkoutOptions.failureUrl,
2595
+ ctx.request,
2596
+ ctx.context.baseURL
2597
+ );
2598
+ const customMetadata = (() => {
2599
+ const merged = { ...effective.metadata ?? {} };
2600
+ if (effective.referenceId !== void 0) {
2601
+ merged.referenceId = effective.referenceId;
2602
+ }
2603
+ return Object.keys(merged).length > 0 ? merged : null;
2604
+ })();
2605
+ const payload = {
2606
+ name: effective.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
2607
+ description: effective.description ?? null,
2608
+ currency: checkoutOptions.currency ?? "SAR",
2609
+ items
2610
+ };
2611
+ if (consumerId !== null) payload.organization_consumer_id = consumerId;
2612
+ if (successUrl) payload.success_redirect_url = successUrl;
2613
+ if (failureUrl) payload.failure_redirect_url = failureUrl;
2614
+ if (effective.maxNumberOfPayments !== void 0) {
2615
+ payload.max_number_of_payments = effective.maxNumberOfPayments;
2616
+ }
2617
+ if (effective.validUntil !== void 0) {
2618
+ payload.valid_until = effective.validUntil;
2619
+ }
2620
+ if (effective.couponIds && effective.couponIds.length > 0) {
2621
+ payload.coupons = effective.couponIds;
2622
+ }
2623
+ if (customMetadata !== null) payload.custom_metadata = customMetadata;
2624
+ if (checkoutOptions.customFields) {
2625
+ payload.custom_fields = checkoutOptions.customFields;
2626
+ }
2627
+ if (checkoutOptions.contactInformationType) {
2628
+ payload.contact_information_type = checkoutOptions.contactInformationType;
2629
+ }
2630
+ try {
2631
+ const link = await client.createPaymentLink(payload);
2632
+ const paymentLinkId = typeof link.id === "string" && link.id.length > 0 ? link.id : null;
2633
+ let url;
2634
+ try {
2635
+ const resolvedUrl = client.getPaymentUrl(link);
2636
+ if (!resolvedUrl) {
2637
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2638
+ message: "StreamPay payment link created but no URL was returned."
2639
+ });
2640
+ }
2641
+ url = resolvedUrl;
2642
+ if (checkoutOptions.onCheckoutCreated) {
2643
+ if (!paymentLinkId) {
2644
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2645
+ message: "StreamPay payment link created but no id was returned."
2646
+ });
2647
+ }
2648
+ try {
2649
+ const callbackData = {
2650
+ user,
2651
+ paymentLinkId,
2652
+ url,
2653
+ payload
2654
+ };
2655
+ if (effective.referenceId !== void 0) {
2656
+ callbackData.referenceId = effective.referenceId;
2657
+ }
2658
+ await checkoutOptions.onCheckoutCreated(callbackData, ctx);
2659
+ } catch (err) {
2660
+ if (err instanceof APIError) throw err;
2661
+ getLogger(ctx).error(`onCheckoutCreated failed: ${formatStreamPayError(err)}`);
2662
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2663
+ message: "Checkout persistence failed."
2664
+ });
2665
+ }
2666
+ }
2667
+ } catch (err) {
2668
+ if (paymentLinkId) {
2669
+ await deactivatePaymentLinkBestEffort(client, paymentLinkId, getLogger(ctx));
2670
+ }
2671
+ throw err;
2672
+ }
2673
+ return ctx.json({
2674
+ url,
2675
+ id: paymentLinkId,
2676
+ redirect: ctx.body.redirect ?? true
2677
+ });
2678
+ } catch (err) {
2679
+ toAPIError(
2680
+ {
2681
+ logPrefix: "checkout creation failed:",
2682
+ userMessage: "StreamPay checkout creation failed."
2683
+ },
2684
+ err,
2685
+ getLogger(ctx)
2686
+ );
2687
+ }
2508
2688
  }
2509
- }
2510
- )
2511
- }
2689
+ )
2690
+ }
2691
+ };
2512
2692
  };
2513
2693
  };
2514
2694
  var DEFAULT_PAGE_SIZE = 100;
@@ -4611,7 +4791,7 @@ var onUserDelete = (options) => async (user, context) => {
4611
4791
 
4612
4792
  // package.json
4613
4793
  var package_default = {
4614
- version: "2.0.0"};
4794
+ version: "2.1.0"};
4615
4795
 
4616
4796
  // src/version.ts
4617
4797
  var version = package_default.version;
@@ -4638,7 +4818,8 @@ var streampay = (options) => {
4638
4818
  streampayConsumerId: {
4639
4819
  type: "string",
4640
4820
  required: false,
4641
- input: false
4821
+ input: false,
4822
+ unique: true
4642
4823
  }
4643
4824
  }
4644
4825
  },