better-auth-streampay 2.1.0 → 2.2.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.
package/dist/index.cjs CHANGED
@@ -45,6 +45,8 @@ var $ERROR_CODES = defineErrorCodes({
45
45
  SUBSCRIPTION_EXPIRED: "The subscription has expired.",
46
46
  SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL: "The subscription is already scheduled to cancel at period end.",
47
47
  SUBSCRIPTION_ALREADY_ON_PLAN: "The subscription is already on the requested plan.",
48
+ SUBSCRIPTION_SEAT_COUNT_INVALID: "The requested seat count is invalid for this plan.",
49
+ SUBSCRIPTION_SEAT_CHANGE_ALREADY_SCHEDULED: "A different subscription change is already scheduled.",
48
50
  SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED: "StreamPay does not support immediate cancellation for active subscriptions.",
49
51
  SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED: "StreamPay only supports period-end cancellation for active subscriptions.",
50
52
  SUBSCRIPTION_PLAN_GROUP_MISMATCH: "Subscription plan changes must stay within the same configured plan group.",
@@ -672,7 +674,8 @@ function projectSubscriptionFields(sub) {
672
674
  }
673
675
  function parseDate(value) {
674
676
  if (!value) return null;
675
- const date = new Date(value);
677
+ const normalized = /[T ]/.test(value) && !/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? `${value}Z` : value;
678
+ const date = new Date(normalized);
676
679
  return Number.isNaN(date.getTime()) ? null : date;
677
680
  }
678
681
  function minorUnitExponent(currency) {
@@ -711,13 +714,19 @@ function amountToSmallestUnit(value, currency) {
711
714
  }
712
715
  var SubscriptionItemSchema = zod.z.object({
713
716
  product: zod.z.object({ id: zod.z.string() }).passthrough().optional(),
714
- product_id: zod.z.string().optional()
717
+ product_id: zod.z.string().optional(),
718
+ quantity: zod.z.number().optional()
715
719
  }).passthrough();
716
720
  function subscriptionItemProductId(item) {
717
721
  const parsed = SubscriptionItemSchema.safeParse(item);
718
722
  if (!parsed.success) return null;
719
723
  return parsed.data.product?.id ?? parsed.data.product_id ?? null;
720
724
  }
725
+ function subscriptionItemQuantity(item) {
726
+ const parsed = SubscriptionItemSchema.safeParse(item);
727
+ if (!parsed.success || parsed.data.quantity === void 0) return null;
728
+ return Number.isSafeInteger(parsed.data.quantity) && parsed.data.quantity > 0 ? parsed.data.quantity : null;
729
+ }
721
730
  function inferPlanFromItems(sub, plans) {
722
731
  if (!Array.isArray(sub.items)) return null;
723
732
  return inferPlanFromItemList(sub.items, plans);
@@ -726,14 +735,32 @@ function inferPlanFromItemList(items, plans) {
726
735
  const productIds = new Set(
727
736
  items.map(subscriptionItemProductId).filter((id) => Boolean(id))
728
737
  );
729
- return plans.list.find((plan) => productIds.has(plan.productId))?.name ?? null;
738
+ const matches = plans.list.filter((plan) => productIds.has(plan.productId));
739
+ if (matches.length > 1) {
740
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
741
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
742
+ message: "StreamPay returned a subscription containing multiple configured plan products."
743
+ });
744
+ }
745
+ return matches[0]?.name ?? null;
730
746
  }
731
747
  function projectPlanFields(sub, plans) {
732
748
  const currentPlan = inferPlanFromItems(sub, plans);
733
- const currentProductId = subscriptionItemProductId(sub.items?.[0]);
734
- const pendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
735
- const pendingProductId = subscriptionItemProductId(sub.pending_change?.target_items?.[0]);
736
749
  const configuredCurrent = currentPlan ? plans.byName.get(currentPlan) : void 0;
750
+ const currentItem = configuredCurrent ? sub.items?.find((item) => subscriptionItemProductId(item) === configuredCurrent.productId) : sub.items?.[0];
751
+ const currentProductId = subscriptionItemProductId(currentItem);
752
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : null;
753
+ const inferredPendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
754
+ const configuredPending = inferredPendingPlan ? plans.byName.get(inferredPendingPlan) : void 0;
755
+ const pendingItem = configuredPending ? sub.pending_change?.target_items?.find(
756
+ (item) => subscriptionItemProductId(item) === configuredPending.productId
757
+ ) : currentProductId ? sub.pending_change?.target_items?.find(
758
+ (item) => subscriptionItemProductId(item) === currentProductId
759
+ ) : sub.pending_change?.target_items?.[0];
760
+ const pendingProductId = subscriptionItemProductId(pendingItem);
761
+ const pendingSeats = pendingItem ? subscriptionItemQuantity(pendingItem) ?? 1 : null;
762
+ const pendingEffectiveAt = parseDate(sub.pending_change?.effective_at);
763
+ const planChanges = Boolean(inferredPendingPlan) && (inferredPendingPlan !== currentPlan || pendingProductId !== currentProductId);
737
764
  return {
738
765
  ...currentPlan ? {
739
766
  plan: currentPlan,
@@ -741,9 +768,12 @@ function projectPlanFields(sub, plans) {
741
768
  productId: currentProductId,
742
769
  group: configuredCurrent?.group ?? null
743
770
  } : currentProductId ? { productId: currentProductId } : {},
744
- pendingPlan,
745
- pendingProductId,
746
- pendingPlanEffectiveAt: parseDate(sub.pending_change?.effective_at)
771
+ ...currentSeats === null ? {} : { seats: currentSeats },
772
+ pendingPlan: planChanges ? inferredPendingPlan : null,
773
+ pendingProductId: planChanges ? pendingProductId : null,
774
+ pendingPlanEffectiveAt: planChanges ? pendingEffectiveAt : null,
775
+ pendingSeats,
776
+ pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
747
777
  };
748
778
  }
749
779
  function subscriptionSlotKey(referenceType, referenceId, group) {
@@ -2944,9 +2974,10 @@ function checkoutInProgressError() {
2944
2974
  });
2945
2975
  }
2946
2976
  async function resumeOrReserveCheckoutSlot(args) {
2947
- const { client, adapter, candidates, activeSlotKey, planName, now, log } = args;
2977
+ const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
2978
+ const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
2948
2979
  const reuseCandidate = candidates.find(
2949
- (row2) => row2.plan === planName && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2980
+ (row2) => matchesCheckout(row2) && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2950
2981
  );
2951
2982
  if (reuseCandidate) {
2952
2983
  let recovery;
@@ -2985,21 +3016,23 @@ async function resumeOrReserveCheckoutSlot(args) {
2985
3016
  where: [{ field: "activeSlotKey", value: activeSlotKey }]
2986
3017
  });
2987
3018
  if (reserved?.status !== "incomplete") throw err;
2988
- let recovery;
2989
- try {
2990
- recovery = await recoverCheckoutUrl(client, reserved);
2991
- } catch (recoveryError) {
2992
- toAPIError(
2993
- {
2994
- logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
2995
- userMessage: "Unable to resume subscription checkout."
2996
- },
2997
- recoveryError,
2998
- log
2999
- );
3000
- }
3001
- if (recovery.kind === "recovered") {
3002
- return { kind: "recovered", row: reserved, url: recovery.url };
3019
+ if (matchesCheckout(reserved)) {
3020
+ let recovery;
3021
+ try {
3022
+ recovery = await recoverCheckoutUrl(client, reserved);
3023
+ } catch (recoveryError) {
3024
+ toAPIError(
3025
+ {
3026
+ logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
3027
+ userMessage: "Unable to resume subscription checkout."
3028
+ },
3029
+ recoveryError,
3030
+ log
3031
+ );
3032
+ }
3033
+ if (recovery.kind === "recovered") {
3034
+ return { kind: "recovered", row: reserved, url: recovery.url };
3035
+ }
3003
3036
  }
3004
3037
  const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3005
3038
  if (!reservationIsStale) throw checkoutInProgressError();
@@ -3025,24 +3058,67 @@ async function resumeOrReserveCheckoutSlot(args) {
3025
3058
  }
3026
3059
  return { kind: "reserved", row, consumerId };
3027
3060
  }
3028
-
3029
- // src/plugins/subscriptions/lifecycle.ts
3030
3061
  function isAlreadyCanceledFreezeError(err) {
3031
3062
  const sdkError = readSdkErrorFields(err);
3032
3063
  const envelope = readEnvelope(sdkError.body);
3033
3064
  return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
3034
3065
  }
3035
3066
  function subscriptionCouponIds(stream) {
3067
+ return couponIdsFromMetadata(stream.coupon_calculation_metadata);
3068
+ }
3069
+ function couponIdsFromMetadata(metadata) {
3036
3070
  const coupons = [];
3037
- for (const coupon of stream.coupon_calculation_metadata?.coupons ?? []) {
3071
+ for (const coupon of metadata?.coupons ?? []) {
3038
3072
  if (coupon.coupon_id) coupons.push(coupon.coupon_id);
3039
3073
  }
3040
3074
  return coupons;
3041
3075
  }
3076
+ function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
3077
+ if (!stream.items?.length) {
3078
+ throw invalidProviderItems("StreamPay returned a subscription without any items.");
3079
+ }
3080
+ const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
3081
+ let matches = 0;
3082
+ const items = stream.items.map((item) => {
3083
+ const productId = subscriptionItemProductId(item);
3084
+ const quantity = item.quantity ?? 1;
3085
+ if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
3086
+ throw invalidProviderItems("StreamPay returned an invalid subscription item.");
3087
+ }
3088
+ const isPlanItem = productId === currentProductId;
3089
+ if (isPlanItem) matches += 1;
3090
+ const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
3091
+ (couponId) => !subscriptionCoupons.has(couponId)
3092
+ );
3093
+ return {
3094
+ product_id: isPlanItem ? targetProductId : productId,
3095
+ quantity: isPlanItem ? targetSeats : quantity,
3096
+ ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
3097
+ };
3098
+ });
3099
+ if (matches !== 1) {
3100
+ throw invalidProviderItems(
3101
+ `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
3102
+ );
3103
+ }
3104
+ return items;
3105
+ }
3106
+ function invalidProviderItems(message) {
3107
+ return new api.APIError("INTERNAL_SERVER_ERROR", {
3108
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3109
+ message
3110
+ });
3111
+ }
3042
3112
  function configuredPlanForSubscription(subscription, plans) {
3043
- return plans.list.find(
3113
+ const matches = plans.list.filter(
3044
3114
  (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
3045
3115
  );
3116
+ if (matches.length > 1) {
3117
+ throw invalidProviderItems(
3118
+ "StreamPay returned a subscription containing multiple configured plan products."
3119
+ );
3120
+ }
3121
+ return matches[0];
3046
3122
  }
3047
3123
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
3048
3124
  var PlanSchema = zod.z.object({
@@ -3065,7 +3141,46 @@ var PlanSchema = zod.z.object({
3065
3141
  message: "has invalid `trialPeriodDays` \u2014 must be an integer from 1 to 365."
3066
3142
  }).optional(),
3067
3143
  group: zod.z.string().min(1, "has an empty `group`.").optional(),
3144
+ seatBilling: zod.z.object({
3145
+ default: zod.z.number().safe().int().positive().optional(),
3146
+ minimum: zod.z.number().safe().int().positive().optional(),
3147
+ maximum: zod.z.number().safe().int().positive().optional(),
3148
+ customerEditable: zod.z.boolean().optional()
3149
+ }).optional(),
3068
3150
  limits: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
3151
+ }).superRefine((plan, ctx) => {
3152
+ const seats = plan.seatBilling;
3153
+ if (!seats) return;
3154
+ const minimum = seats.minimum ?? 1;
3155
+ const defaultSeats = seats.default ?? minimum;
3156
+ if (seats.maximum !== void 0 && seats.maximum < minimum) {
3157
+ ctx.addIssue({
3158
+ code: "custom",
3159
+ path: ["seatBilling", "maximum"],
3160
+ message: "must be greater than or equal to `minimum`."
3161
+ });
3162
+ }
3163
+ if (defaultSeats < minimum || seats.maximum !== void 0 && defaultSeats > seats.maximum) {
3164
+ ctx.addIssue({
3165
+ code: "custom",
3166
+ path: ["seatBilling", "default"],
3167
+ message: "must be within the configured minimum and maximum."
3168
+ });
3169
+ }
3170
+ if (seats.customerEditable && (seats.minimum === void 0 || seats.maximum === void 0)) {
3171
+ ctx.addIssue({
3172
+ code: "custom",
3173
+ path: ["seatBilling", "customerEditable"],
3174
+ message: "requires explicit `minimum` and `maximum` bounds for hosted checkout editing."
3175
+ });
3176
+ }
3177
+ if (seats.maximum !== void 0 && !Number.isSafeInteger(plan.priceInSmallestUnit * seats.maximum)) {
3178
+ ctx.addIssue({
3179
+ code: "custom",
3180
+ path: ["seatBilling", "maximum"],
3181
+ message: "produces an unsafe total with `priceInSmallestUnit`."
3182
+ });
3183
+ }
3069
3184
  });
3070
3185
  var PlansSchema = zod.z.array(PlanSchema).nonempty("`plans` resolved to an empty list. Provide at least one plan.").superRefine((plans, ctx) => {
3071
3186
  const seenNames = /* @__PURE__ */ new Set();
@@ -3103,26 +3218,10 @@ function buildIndex(list) {
3103
3218
  for (const plan of list) byName.set(plan.name, plan);
3104
3219
  return { list, byName };
3105
3220
  }
3106
- function createPlanResolver(plans) {
3107
- let cached = null;
3108
- let inFlight = null;
3109
- return async function getPlans() {
3110
- if (cached) return cached;
3111
- if (inFlight) return inFlight;
3112
- if (!plans) throw new TypeError("subscriptions(): `plans` is required.");
3113
- inFlight = (async () => {
3114
- const list = typeof plans === "function" ? await plans() : plans;
3115
- validatePlansShape(list);
3116
- const resolved = buildIndex(list);
3117
- cached = resolved;
3118
- return resolved;
3119
- })();
3120
- try {
3121
- return await inFlight;
3122
- } finally {
3123
- inFlight = null;
3124
- }
3125
- };
3221
+ async function resolvePlans(plans) {
3222
+ const list = typeof plans === "function" ? await plans() : plans;
3223
+ validatePlansShape(list);
3224
+ return buildIndex(list);
3126
3225
  }
3127
3226
  function hasSubscriptionAccess(subscription, accessStatuses = DEFAULT_ACCESS_STATUSES) {
3128
3227
  return accessStatuses.includes(subscription.status);
@@ -3169,6 +3268,15 @@ var CheckLimitQuery = zod.z.object({
3169
3268
  count: zod.z.coerce.number().int().min(0),
3170
3269
  group: zod.z.string().min(1).optional()
3171
3270
  });
3271
+ function presentSubscription(row, plans) {
3272
+ return {
3273
+ ...row,
3274
+ // The column is nullable during safe rolling migrations. Keep the public
3275
+ // contract stable while applications backfill legacy rows to one seat.
3276
+ seats: row.seats ?? 1,
3277
+ plan: plans.byName.get(row.plan) ?? null
3278
+ };
3279
+ }
3172
3280
  async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
3173
3281
  const user = requireUser(ctx);
3174
3282
  const reference = resolveReference(user, query);
@@ -3219,12 +3327,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3219
3327
  ]
3220
3328
  });
3221
3329
  const plans = await plansRef();
3222
- return ctx.json(
3223
- rows.map((row) => ({
3224
- ...row,
3225
- plan: plans.byName.get(row.plan) ?? null
3226
- }))
3227
- );
3330
+ return ctx.json(rows.map((row) => presentSubscription(row, plans)));
3228
3331
  }
3229
3332
  ),
3230
3333
  currentSubscription: api.createAuthEndpoint(
@@ -3243,7 +3346,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3243
3346
  );
3244
3347
  if (!live) return ctx.json(null);
3245
3348
  const plans = await plansRef();
3246
- return ctx.json({ ...live, plan: plans.byName.get(live.plan) ?? null });
3349
+ return ctx.json(presentSubscription(live, plans));
3247
3350
  }
3248
3351
  ),
3249
3352
  hasSubscriptionFeature: api.createAuthEndpoint(
@@ -3278,16 +3381,63 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3278
3381
  )
3279
3382
  };
3280
3383
  }
3384
+ function resolveSeatCount(plan, requested) {
3385
+ const seats = requested ?? plan.seatBilling?.default ?? plan.seatBilling?.minimum ?? 1;
3386
+ const minimum = plan.seatBilling?.minimum ?? 1;
3387
+ const maximum = plan.seatBilling?.maximum;
3388
+ if (!Number.isSafeInteger(seats) || seats < minimum || maximum !== void 0 && seats > maximum) {
3389
+ const range = maximum === void 0 ? `${minimum} or more` : `${minimum}\u2013${maximum}`;
3390
+ throw new api.APIError("BAD_REQUEST", {
3391
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
3392
+ message: `Plan "${plan.name}" requires a safe-integer seat count in the range ${range}.`
3393
+ });
3394
+ }
3395
+ return seats;
3396
+ }
3397
+ function quotedSeatTotal(plan, seats) {
3398
+ const total = plan.priceInSmallestUnit * seats;
3399
+ if (!Number.isSafeInteger(total)) {
3400
+ throw new api.APIError("BAD_REQUEST", {
3401
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
3402
+ message: `The quoted total for ${seats} seats exceeds JavaScript's safe-integer range.`
3403
+ });
3404
+ }
3405
+ return total;
3406
+ }
3407
+ function buildSeatCheckoutItem(plan, seats) {
3408
+ if (!plan.seatBilling?.customerEditable) {
3409
+ return {
3410
+ product_id: plan.productId,
3411
+ quantity: seats,
3412
+ allow_custom_quantity: false
3413
+ };
3414
+ }
3415
+ const minimum = plan.seatBilling.minimum;
3416
+ const maximum = plan.seatBilling.maximum;
3417
+ if (minimum === void 0 || maximum === void 0) {
3418
+ throw new TypeError(
3419
+ `Plan "${plan.name}" must configure seatBilling.minimum and seatBilling.maximum when customerEditable is true.`
3420
+ );
3421
+ }
3422
+ return {
3423
+ product_id: plan.productId,
3424
+ quantity: seats,
3425
+ allow_custom_quantity: true,
3426
+ min_quantity: minimum,
3427
+ max_quantity: maximum
3428
+ };
3429
+ }
3281
3430
 
3282
3431
  // src/plugins/subscriptions/endpoints.ts
3283
3432
  var SUBSCRIPTION_MODEL6 = "subscription";
3284
3433
  var UpgradeBody = zod.z.object({
3285
3434
  plan: zod.z.string().min(1),
3435
+ seats: zod.z.number().int().positive().safe().optional(),
3286
3436
  referenceId: zod.z.string().min(1).optional(),
3287
3437
  referenceType: zod.z.enum(["user", "organization", "custom"]).optional(),
3288
3438
  successUrl: zod.z.string().url().optional(),
3289
3439
  failureUrl: zod.z.string().url().optional()
3290
- });
3440
+ }).strict();
3291
3441
  var SuccessQuery = zod.z.object({
3292
3442
  subscriptionId: zod.z.string().min(1)
3293
3443
  });
@@ -3298,7 +3448,12 @@ var CancelBody = zod.z.object({
3298
3448
  });
3299
3449
  var ChangePlanBody = zod.z.object({
3300
3450
  subscriptionId: zod.z.string().min(1),
3301
- plan: zod.z.string().min(1)
3451
+ plan: zod.z.string().min(1),
3452
+ seats: zod.z.number().int().positive().safe().optional()
3453
+ }).strict();
3454
+ var UpdateSeatsBody = zod.z.object({
3455
+ subscriptionId: zod.z.string().min(1),
3456
+ seats: zod.z.number().int().positive().safe()
3302
3457
  }).strict();
3303
3458
  var FreezeBody = zod.z.object({
3304
3459
  subscriptionId: zod.z.string().min(1),
@@ -3328,11 +3483,72 @@ function isCheckoutSubscriptionCandidate(subscription, row, productId) {
3328
3483
  return true;
3329
3484
  }
3330
3485
  if (!subscription.created_at || !(row.createdAt instanceof Date)) return false;
3331
- const createdAt = new Date(subscription.created_at).getTime();
3332
- return Number.isFinite(createdAt) && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
3486
+ const createdAt = parseDate(subscription.created_at)?.getTime();
3487
+ return createdAt !== void 0 && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
3333
3488
  }
3334
3489
  function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3335
3490
  const client = options.client;
3491
+ const cancelPendingChangeEndpoint = (path) => api.createAuthEndpoint(
3492
+ path,
3493
+ {
3494
+ method: "POST",
3495
+ body: UnfreezeBody,
3496
+ use: [api.sessionMiddleware]
3497
+ },
3498
+ async (ctx) => {
3499
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3500
+ ctx,
3501
+ ctx.body.subscriptionId,
3502
+ subsOptions,
3503
+ "cancel-plan-change"
3504
+ );
3505
+ try {
3506
+ const plans = await plansRef();
3507
+ const current = await client.getSubscription(row.streampaySubscriptionId);
3508
+ if (!current.pending_change) {
3509
+ await adapter.update({
3510
+ model: SUBSCRIPTION_MODEL6,
3511
+ update: {
3512
+ ...projectSubscriptionAgainstExisting(row, current),
3513
+ ...projectPlanFields(current, plans),
3514
+ pendingPlan: null,
3515
+ pendingProductId: null,
3516
+ pendingPlanEffectiveAt: null,
3517
+ pendingSeats: null,
3518
+ pendingSeatsEffectiveAt: null
3519
+ },
3520
+ where: [{ field: "id", value: row.id }]
3521
+ });
3522
+ return ctx.json({ canceled: true, reused: true, subscription: current });
3523
+ }
3524
+ await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3525
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3526
+ await adapter.update({
3527
+ model: SUBSCRIPTION_MODEL6,
3528
+ update: {
3529
+ ...projectSubscriptionAgainstExisting(row, stream),
3530
+ ...projectPlanFields(stream, plans),
3531
+ pendingPlan: null,
3532
+ pendingProductId: null,
3533
+ pendingPlanEffectiveAt: null,
3534
+ pendingSeats: null,
3535
+ pendingSeatsEffectiveAt: null
3536
+ },
3537
+ where: [{ field: "id", value: row.id }]
3538
+ });
3539
+ return ctx.json({ canceled: true, reused: false, subscription: stream });
3540
+ } catch (err) {
3541
+ toAPIError(
3542
+ {
3543
+ logPrefix: `cancel pending subscription change failed for row=${row.id}:`,
3544
+ userMessage: "Canceling the pending subscription change failed."
3545
+ },
3546
+ err,
3547
+ getLogger(ctx)
3548
+ );
3549
+ }
3550
+ }
3551
+ );
3336
3552
  return {
3337
3553
  ...buildSubscriptionReadEndpoints(subsOptions, plansRef),
3338
3554
  upgradeSubscription: api.createAuthEndpoint(
@@ -3355,6 +3571,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3355
3571
  message: `Plan "${ctx.body.plan}" is not configured.`
3356
3572
  });
3357
3573
  }
3574
+ const seats = resolveSeatCount(plan, ctx.body.seats);
3575
+ const quotedTotal = quotedSeatTotal(plan, seats);
3358
3576
  const adapter = getAdapter2(ctx);
3359
3577
  const existingActive = await adapter.findMany({
3360
3578
  model: SUBSCRIPTION_MODEL6,
@@ -3392,6 +3610,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3392
3610
  candidates: existingActive,
3393
3611
  activeSlotKey,
3394
3612
  planName: plan.name,
3613
+ seats,
3395
3614
  now: Date.now(),
3396
3615
  log: getLogger(ctx),
3397
3616
  createReservation: async () => {
@@ -3411,13 +3630,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3411
3630
  planVersion: plan.version ?? null,
3412
3631
  productId: plan.productId,
3413
3632
  group: plan.group ?? null,
3633
+ seats,
3414
3634
  streampayConsumerId: consumerId2,
3415
3635
  streampayPaymentLinkId: null,
3416
3636
  status: "incomplete",
3417
3637
  providerStatus: null,
3418
3638
  billingStatus: "current",
3419
- amountInSmallestUnit: plan.priceInSmallestUnit,
3420
- originalAmountInSmallestUnit: plan.priceInSmallestUnit,
3639
+ amountInSmallestUnit: quotedTotal,
3640
+ originalAmountInSmallestUnit: quotedTotal,
3421
3641
  currency: plan.currency ?? "SAR",
3422
3642
  billingInterval: plan.billingInterval,
3423
3643
  billingIntervalCount: plan.billingIntervalCount ?? 1,
@@ -3433,6 +3653,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3433
3653
  pendingPlan: null,
3434
3654
  pendingProductId: null,
3435
3655
  pendingPlanEffectiveAt: null,
3656
+ pendingSeats: null,
3657
+ pendingSeatsEffectiveAt: null,
3436
3658
  endedAt: null,
3437
3659
  frozenAt: null,
3438
3660
  freezeEndAt: null,
@@ -3451,14 +3673,15 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3451
3673
  redirect: true,
3452
3674
  reused: true,
3453
3675
  status: reservation.row.status,
3454
- plan: reservation.row.plan
3676
+ plan: reservation.row.plan,
3677
+ seats: reservation.row.seats ?? 1
3455
3678
  });
3456
3679
  }
3457
3680
  const { row, consumerId } = reservation;
3458
3681
  const linkInput = {
3459
3682
  name: `Subscription \u2014 ${plan.name}`,
3460
3683
  currency: plan.currency ?? "SAR",
3461
- items: [{ product_id: plan.productId, quantity: 1, allow_custom_quantity: false }],
3684
+ items: [buildSeatCheckoutItem(plan, seats)],
3462
3685
  max_number_of_payments: 1,
3463
3686
  organization_consumer_id: consumerId,
3464
3687
  custom_metadata: {
@@ -3551,7 +3774,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3551
3774
  redirect: true,
3552
3775
  reused: false,
3553
3776
  status: "incomplete",
3554
- plan: plan.name
3777
+ plan: plan.name,
3778
+ seats
3555
3779
  });
3556
3780
  }
3557
3781
  ),
@@ -3622,6 +3846,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3622
3846
  model: SUBSCRIPTION_MODEL6,
3623
3847
  update: {
3624
3848
  ...projectSubscriptionFields(match),
3849
+ ...projectPlanFields(match, plans),
3625
3850
  planVersion: plan.version ?? null,
3626
3851
  productId: plan.productId,
3627
3852
  billingStatus: "current",
@@ -3733,8 +3958,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3733
3958
  }
3734
3959
  try {
3735
3960
  const stream = await client.getSubscription(row.streampaySubscriptionId);
3736
- const currentPlan = configuredPlanForSubscription(stream, plans);
3737
- const currentGroup = currentPlan?.group ?? row.group;
3961
+ const currentPlan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
3962
+ if (!currentPlan) {
3963
+ throw new api.APIError("BAD_REQUEST", {
3964
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3965
+ message: "The current StreamPay product is not a configured subscription plan."
3966
+ });
3967
+ }
3968
+ const currentGroup = currentPlan.group ?? row.group;
3738
3969
  if (currentGroup !== (nextPlan.group ?? null)) {
3739
3970
  throw new api.APIError("BAD_REQUEST", {
3740
3971
  code: $ERROR_CODES.SUBSCRIPTION_PLAN_GROUP_MISMATCH.code,
@@ -3747,27 +3978,35 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3747
3978
  message: "The subscription is scheduled to cancel. Uncancel it before scheduling a plan change."
3748
3979
  });
3749
3980
  }
3750
- const currentProductIsRequestedPlan = stream.items?.some(
3751
- (item) => subscriptionItemProductId(item) === nextPlan.productId
3981
+ const currentItem = stream.items?.find(
3982
+ (item) => subscriptionItemProductId(item) === currentPlan.productId
3752
3983
  );
3753
- if (currentProductIsRequestedPlan && !stream.pending_change) {
3984
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
3985
+ const nextSeats = resolveSeatCount(nextPlan, ctx.body.seats ?? currentSeats ?? 1);
3986
+ const currentProductIsRequestedPlan = currentPlan.productId === nextPlan.productId;
3987
+ if (currentProductIsRequestedPlan && currentSeats === nextSeats && !stream.pending_change) {
3754
3988
  throw new api.APIError("BAD_REQUEST", {
3755
3989
  code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ON_PLAN.code,
3756
- message: `Already on plan "${nextPlan.name}".`
3990
+ message: `Already on plan "${nextPlan.name}" with ${nextSeats} seats.`
3757
3991
  });
3758
3992
  }
3759
3993
  const pendingTargets = stream.pending_change?.target_items ?? [];
3760
- const pendingTargetIsRequestedPlan = pendingTargets.some(
3994
+ const pendingTarget = pendingTargets.find(
3761
3995
  (item) => subscriptionItemProductId(item) === nextPlan.productId
3762
3996
  );
3763
- if (pendingTargetIsRequestedPlan) {
3997
+ const pendingTargetMatches = Boolean(pendingTarget) && (subscriptionItemQuantity(pendingTarget) ?? 1) === nextSeats;
3998
+ if (pendingTargetMatches) {
3999
+ const effectiveAt2 = stream.pending_change?.effective_at ?? null;
3764
4000
  await adapter.update({
3765
4001
  model: SUBSCRIPTION_MODEL6,
3766
4002
  update: {
3767
4003
  ...projectSubscriptionAgainstExisting(row, stream),
3768
- pendingPlan: nextPlan.name,
3769
- pendingProductId: nextPlan.productId,
3770
- pendingPlanEffectiveAt: stream.pending_change?.effective_at ? new Date(stream.pending_change.effective_at) : null
4004
+ ...projectPlanFields(stream, plans),
4005
+ pendingPlan: currentPlan.productId === nextPlan.productId ? null : nextPlan.name,
4006
+ pendingProductId: currentPlan.productId === nextPlan.productId ? null : nextPlan.productId,
4007
+ pendingPlanEffectiveAt: currentPlan.productId !== nextPlan.productId && effectiveAt2 ? parseDate(effectiveAt2) : null,
4008
+ pendingSeats: nextSeats,
4009
+ pendingSeatsEffectiveAt: parseDate(effectiveAt2)
3771
4010
  },
3772
4011
  where: [{ field: "id", value: row.id }]
3773
4012
  });
@@ -3775,7 +4014,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3775
4014
  mode: "at_period_end",
3776
4015
  subscriptionId: row.id,
3777
4016
  plan: nextPlan.name,
3778
- effectiveAt: stream.pending_change?.effective_at ?? null,
4017
+ seats: nextSeats,
4018
+ effectiveAt: effectiveAt2,
3779
4019
  pendingChange: stream.pending_change,
3780
4020
  reused: true
3781
4021
  });
@@ -3787,28 +4027,36 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3787
4027
  });
3788
4028
  }
3789
4029
  const patch = {
3790
- items: [{ product_id: nextPlan.productId, quantity: 1 }],
4030
+ items: subscriptionItemsForUpdate(
4031
+ stream,
4032
+ currentPlan.productId,
4033
+ nextPlan.productId,
4034
+ nextSeats
4035
+ ),
3791
4036
  coupons: subscriptionCouponIds(stream),
3792
4037
  recurring_interval: nextPlan.billingInterval,
3793
4038
  recurring_interval_count: nextPlan.billingIntervalCount ?? 1
3794
4039
  };
3795
4040
  const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3796
- const effectiveAt = result.pending_change?.effective_at ?? result.current_period_end ?? null;
4041
+ const pending = Boolean(result.pending_change);
4042
+ const effectiveAt = result.pending_change?.effective_at ?? null;
4043
+ const planProjection = projectPlanFields(result, plans);
3797
4044
  await adapter.update({
3798
4045
  model: SUBSCRIPTION_MODEL6,
3799
4046
  update: {
3800
4047
  ...projectSubscriptionAgainstExisting(row, result),
3801
- pendingPlan: nextPlan.name,
3802
- pendingProductId: nextPlan.productId,
3803
- pendingPlanEffectiveAt: effectiveAt ? new Date(effectiveAt) : null,
4048
+ ...planProjection,
3804
4049
  updatedAt: /* @__PURE__ */ new Date()
3805
4050
  },
3806
4051
  where: [{ field: "id", value: row.id }]
3807
4052
  });
4053
+ const providerPlan = pending ? planProjection.pendingPlan ?? planProjection.plan ?? row.plan : planProjection.plan ?? row.plan;
4054
+ const providerSeats = pending ? planProjection.pendingSeats ?? nextSeats : planProjection.seats ?? row.seats ?? nextSeats;
3808
4055
  return ctx.json({
3809
- mode: "at_period_end",
4056
+ mode: pending ? "at_period_end" : "immediate",
3810
4057
  subscriptionId: row.id,
3811
- plan: nextPlan.name,
4058
+ plan: providerPlan,
4059
+ seats: providerSeats,
3812
4060
  effectiveAt,
3813
4061
  pendingChange: result.pending_change ?? null,
3814
4062
  subscription: result,
@@ -3826,11 +4074,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3826
4074
  }
3827
4075
  }
3828
4076
  ),
3829
- cancelSubscriptionPlanChange: api.createAuthEndpoint(
3830
- "/subscription/change-plan/cancel",
4077
+ updateSubscriptionSeats: api.createAuthEndpoint(
4078
+ "/subscription/update-seats",
3831
4079
  {
3832
4080
  method: "POST",
3833
- body: UnfreezeBody,
4081
+ body: UpdateSeatsBody,
3834
4082
  use: [api.sessionMiddleware]
3835
4083
  },
3836
4084
  async (ctx) => {
@@ -3838,27 +4086,107 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3838
4086
  ctx,
3839
4087
  ctx.body.subscriptionId,
3840
4088
  subsOptions,
3841
- "cancel-plan-change"
4089
+ "update-seats"
3842
4090
  );
4091
+ const plans = await plansRef();
3843
4092
  try {
3844
- await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3845
4093
  const stream = await client.getSubscription(row.streampaySubscriptionId);
4094
+ const plan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
4095
+ if (!plan) {
4096
+ throw new api.APIError("BAD_REQUEST", {
4097
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
4098
+ message: "The current StreamPay product is not a configured subscription plan."
4099
+ });
4100
+ }
4101
+ if (stream.cancel_at_period_end) {
4102
+ throw new api.APIError("CONFLICT", {
4103
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL.code,
4104
+ message: "Uncancel the subscription before scheduling a seat change."
4105
+ });
4106
+ }
4107
+ const seats = resolveSeatCount(plan, ctx.body.seats);
4108
+ const currentItem = stream.items?.find(
4109
+ (item) => subscriptionItemProductId(item) === plan.productId
4110
+ );
4111
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
4112
+ const pendingTarget = stream.pending_change?.target_items?.find(
4113
+ (item) => subscriptionItemProductId(item) === plan.productId
4114
+ );
4115
+ if (stream.pending_change) {
4116
+ if (pendingTarget && (subscriptionItemQuantity(pendingTarget) ?? 1) === seats) {
4117
+ const effectiveAt2 = stream.pending_change.effective_at ?? null;
4118
+ await adapter.update({
4119
+ model: SUBSCRIPTION_MODEL6,
4120
+ update: {
4121
+ ...projectSubscriptionAgainstExisting(row, stream),
4122
+ ...projectPlanFields(stream, plans)
4123
+ },
4124
+ where: [{ field: "id", value: row.id }]
4125
+ });
4126
+ return ctx.json({
4127
+ mode: "at_period_end",
4128
+ subscriptionId: row.id,
4129
+ seats,
4130
+ effectiveAt: effectiveAt2,
4131
+ pendingChange: stream.pending_change,
4132
+ reused: true
4133
+ });
4134
+ }
4135
+ throw new api.APIError("CONFLICT", {
4136
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_CHANGE_ALREADY_SCHEDULED.code,
4137
+ message: "A different subscription change is pending. Cancel it before scheduling this seat count."
4138
+ });
4139
+ }
4140
+ if (currentSeats === seats) {
4141
+ await adapter.update({
4142
+ model: SUBSCRIPTION_MODEL6,
4143
+ update: {
4144
+ ...projectSubscriptionAgainstExisting(row, stream),
4145
+ ...projectPlanFields(stream, plans)
4146
+ },
4147
+ where: [{ field: "id", value: row.id }]
4148
+ });
4149
+ return ctx.json({
4150
+ mode: "current",
4151
+ subscriptionId: row.id,
4152
+ seats,
4153
+ effectiveAt: null,
4154
+ pendingChange: null,
4155
+ reused: true
4156
+ });
4157
+ }
4158
+ const patch = {
4159
+ items: subscriptionItemsForUpdate(stream, plan.productId, plan.productId, seats),
4160
+ coupons: subscriptionCouponIds(stream)
4161
+ };
4162
+ const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
4163
+ const pending = Boolean(result.pending_change);
4164
+ const effectiveAt = result.pending_change?.effective_at ?? null;
4165
+ const planProjection = projectPlanFields(result, plans);
3846
4166
  await adapter.update({
3847
4167
  model: SUBSCRIPTION_MODEL6,
3848
4168
  update: {
3849
- ...projectSubscriptionAgainstExisting(row, stream),
3850
- pendingPlan: null,
3851
- pendingProductId: null,
3852
- pendingPlanEffectiveAt: null
4169
+ ...projectSubscriptionAgainstExisting(row, result),
4170
+ ...planProjection,
4171
+ updatedAt: /* @__PURE__ */ new Date()
3853
4172
  },
3854
4173
  where: [{ field: "id", value: row.id }]
3855
4174
  });
3856
- return ctx.json({ canceled: true, subscription: stream });
4175
+ const providerSeats = pending ? planProjection.pendingSeats ?? seats : planProjection.seats ?? row.seats ?? seats;
4176
+ return ctx.json({
4177
+ mode: pending ? "at_period_end" : "immediate",
4178
+ subscriptionId: row.id,
4179
+ seats: providerSeats,
4180
+ effectiveAt,
4181
+ pendingChange: result.pending_change ?? null,
4182
+ subscription: result,
4183
+ reused: false
4184
+ });
3857
4185
  } catch (err) {
3858
4186
  toAPIError(
3859
4187
  {
3860
- logPrefix: `cancel plan change failed for row=${row.id}:`,
3861
- userMessage: "Canceling the scheduled plan change failed."
4188
+ logPrefix: `update-seats failed for row=${row.id}:`,
4189
+ userMessage: "Seat change scheduling failed."
3862
4190
  },
3863
4191
  err,
3864
4192
  getLogger(ctx)
@@ -3866,6 +4194,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3866
4194
  }
3867
4195
  }
3868
4196
  ),
4197
+ cancelSubscriptionPlanChange: cancelPendingChangeEndpoint("/subscription/change-plan/cancel"),
4198
+ cancelSubscriptionPendingChange: cancelPendingChangeEndpoint(
4199
+ "/subscription/pending-change/cancel"
4200
+ ),
3869
4201
  uncancelSubscription: api.createAuthEndpoint(
3870
4202
  "/subscription/uncancel",
3871
4203
  {
@@ -3965,9 +4297,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3965
4297
  const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
3966
4298
  const active = freezes.data?.find((freeze) => {
3967
4299
  if (!freeze.id || !freeze.freeze_start_datetime) return false;
3968
- const start = new Date(freeze.freeze_start_datetime).getTime();
3969
- const end = freeze.freeze_end_datetime ? new Date(freeze.freeze_end_datetime).getTime() : Number.POSITIVE_INFINITY;
3970
- return start <= nowMs && nowMs <= end;
4300
+ const start = parseDate(freeze.freeze_start_datetime)?.getTime();
4301
+ const end = freeze.freeze_end_datetime ? parseDate(freeze.freeze_end_datetime)?.getTime() : Number.POSITIVE_INFINITY;
4302
+ return start !== void 0 && end !== void 0 && start <= nowMs && nowMs <= end;
3971
4303
  });
3972
4304
  if (!active?.id || !active.freeze_start_datetime) {
3973
4305
  throw new api.APIError("BAD_REQUEST", {
@@ -4107,6 +4439,11 @@ var subscriptionTable = {
4107
4439
  required: false,
4108
4440
  index: true
4109
4441
  },
4442
+ seats: {
4443
+ type: "number",
4444
+ required: false,
4445
+ defaultValue: 1
4446
+ },
4110
4447
  amountInSmallestUnit: {
4111
4448
  type: "number",
4112
4449
  required: false
@@ -4195,6 +4532,14 @@ var subscriptionTable = {
4195
4532
  type: "date",
4196
4533
  required: false
4197
4534
  },
4535
+ pendingSeats: {
4536
+ type: "number",
4537
+ required: false
4538
+ },
4539
+ pendingSeatsEffectiveAt: {
4540
+ type: "date",
4541
+ required: false
4542
+ },
4198
4543
  endedAt: {
4199
4544
  type: "date",
4200
4545
  required: false
@@ -4329,13 +4674,13 @@ function subscriptions(subsOptions) {
4329
4674
  }
4330
4675
  const dedupeEnabled = subsOptions.enableWebhookEventTable !== false;
4331
4676
  return (options, registry) => {
4332
- const resolvePlans = createPlanResolver(subsOptions.plans);
4677
+ const plansRef = () => resolvePlans(subsOptions.plans);
4333
4678
  if (registry) {
4334
4679
  registry.subscriptionWebhookSync = async (ctx, payload, meta) => {
4335
4680
  const syncCtx = {
4336
4681
  context: ctx.context
4337
4682
  };
4338
- const plans = await resolvePlans();
4683
+ const plans = await plansRef();
4339
4684
  try {
4340
4685
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
4341
4686
  dedupe: dedupeEnabled,
@@ -4391,7 +4736,7 @@ function subscriptions(subsOptions) {
4391
4736
  });
4392
4737
  }
4393
4738
  const payload = parsedPayload;
4394
- const plans = await resolvePlans();
4739
+ const plans = await plansRef();
4395
4740
  const claimed = await claimWebhookEventForReplay(syncCtx, row);
4396
4741
  if (!claimed?.lockedBy) {
4397
4742
  throw new api.APIError("CONFLICT", {
@@ -4428,7 +4773,7 @@ function subscriptions(subsOptions) {
4428
4773
  ...dedupeEnabled ? webhookEventTable : {}
4429
4774
  };
4430
4775
  return {
4431
- endpoints: buildSubscriptionEndpoints(options, subsOptions, resolvePlans),
4776
+ endpoints: buildSubscriptionEndpoints(options, subsOptions, plansRef),
4432
4777
  schema
4433
4778
  };
4434
4779
  };
@@ -4793,7 +5138,7 @@ var onUserDelete = (options) => async (user, context) => {
4793
5138
 
4794
5139
  // package.json
4795
5140
  var package_default = {
4796
- version: "2.1.0"};
5141
+ version: "2.2.1"};
4797
5142
 
4798
5143
  // src/version.ts
4799
5144
  var version = package_default.version;